Beispiel #1
0
        public void InitializeWillNotOverwriteExistingCustomDimension()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");
            envMock.Setup(env => env.ContainerID).Returns("Cid");

            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            Mock <ITelemetryKeyCache> keyCacheMock = new Mock <ITelemetryKeyCache>();

            keyCacheMock.Setup(c => c.GetProcessedKey(It.IsAny <string>())).Returns <string>(input => input);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(
                envFactoryMock.Object,
                GetOptions(TimeSpan.FromSeconds(1)),
                SDKVersionUtils.Instance,
                keyCacheMock.Object);
            ITelemetry         telemetry = new TraceTelemetry();
            ISupportProperties telemetryWithProperties = telemetry as ISupportProperties;

            telemetryWithProperties.Properties["K8s.Container.ID"] = "Existing Cid";
            target.Initialize(telemetry);

            Assert.Equal("Existing Cid", telemetryWithProperties.Properties["K8s.Container.ID"]);
        }
Beispiel #2
0
        public void InitializeWithEmptyForOptionalPropertyDoesNotLogError()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            envMock.Setup(env => env.ContainerName).Returns("CName");
            envMock.Setup(env => env.PodID).Returns("Pid");
            envMock.Setup(env => env.PodName).Returns("PName");
            envMock.Setup(env => env.PodLabels).Returns("PLabels");
            // The following properties are optional.
            envMock.Setup(env => env.ReplicaSetUid).Returns <string>(null);
            envMock.Setup(env => env.ReplicaSetName).Returns <string>(null);
            envMock.Setup(env => env.DeploymentUid).Returns <string>(null);
            envMock.Setup(env => env.DeploymentName).Returns <string>(null);
            envMock.Setup(env => env.NodeUid).Returns("Nid");
            envMock.Setup(env => env.NodeName).Returns("NName");

            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            var loggerMock = new Mock <ILogger <KubernetesTelemetryInitializer> >();

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envFactoryMock.Object, TimeSpan.FromSeconds(1), SDKVersionUtils.Instance, loggerMock.Object);
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);
            loggerMock.Verify(l => l.Log(LogLevel.Error, 0, It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Never());
        }
Beispiel #3
0
        public void ShouldUseTheValueByTheKeyProcessorForTelemetry()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello.RoleName");
            envMock.Setup(env => env.ContainerID).Returns("Hello.Cid");

            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            Mock <ITelemetryKeyCache> keyCacheMock = new Mock <ITelemetryKeyCache>();

            keyCacheMock.Setup(c => c.GetProcessedKey(It.IsAny <string>())).Returns <string>(input => input.Replace('.', '_'));

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(
                envFactoryMock.Object,
                GetOptions(TimeSpan.FromSeconds(1)),
                SDKVersionUtils.Instance,
                keyCacheMock.Object);
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);

            ISupportProperties telemetryWithProperties = telemetry as ISupportProperties;

            Assert.False(telemetryWithProperties.Properties.ContainsKey("Kubernetes.Container.ID"));
            Assert.True(telemetryWithProperties.Properties.ContainsKey("Kubernetes_Container_ID"));
        }
Beispiel #4
0
        public void TimeoutGettingK8sEnvNoException()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(envMock.Object, TimeSpan.FromMinutes(1));
            Mock <ITelemetryKeyCache> keyCacheMock = new Mock <ITelemetryKeyCache>();

            keyCacheMock.Setup(c => c.GetProcessedKey(It.IsAny <string>())).Returns <string>(input => input);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(
                envFactoryMock.Object,
                GetOptions(TimeSpan.FromSeconds(1)),
                SDKVersionUtils.Instance,
                keyCacheMock.Object);

            ITelemetry         telemetry = new TraceTelemetry();
            ISupportProperties telemetryWithProperties = telemetry as ISupportProperties;

            telemetryWithProperties.Properties["K8s.Container.ID"] = "No Crash";
            target.Initialize(telemetry);

            Assert.Equal("No Crash", telemetryWithProperties.Properties["K8s.Container.ID"]);
        }
Beispiel #5
0
        public void ConstructorSetK8sEnvironment()
        {
            var envMock = new Mock <IK8sEnvironment>();
            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(null, envMock.Object);

            Assert.NotNull(target.K8sEnvironment);
            Assert.Equal(envMock.Object, target.K8sEnvironment);
        }
        public void ConstructorSetsNullGetsNull()
        {
            Exception ex = Assert.Throws <ArgumentNullException>(() =>
            {
                KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(null, GetLogger());
            });

            Assert.Equal("Value cannot be null.\r\nParameter name: k8sEnv", ex.Message);
        }
Beispiel #7
0
        public void ConstructorSetsNullGetsNull()
        {
            Exception ex = Assert.Throws <ArgumentNullException>(() =>
            {
                KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(null, TimeSpan.FromSeconds(1), SDKVersionUtils.Instance, GetLogger());
            });

            Assert.Equal("Value cannot be null.\r\nParameter name: k8sEnvFactory", ex.Message);
        }
Beispiel #8
0
        public void InitializeSetsCustomDimensions()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            envMock.Setup(env => env.ContainerName).Returns("CName");
            envMock.Setup(env => env.PodID).Returns("Pid");
            envMock.Setup(env => env.PodName).Returns("PName");
            envMock.Setup(env => env.PodLabels).Returns("PLabels");
            envMock.Setup(env => env.ReplicaSetUid).Returns("Rid");
            envMock.Setup(env => env.ReplicaSetName).Returns("RName");
            envMock.Setup(env => env.DeploymentUid).Returns("Did");
            envMock.Setup(env => env.DeploymentName).Returns("DName");
            envMock.Setup(env => env.NodeUid).Returns("Nid");
            envMock.Setup(env => env.NodeName).Returns("NName");
            envMock.Setup(env => env.PodNamespace).Returns("PNS");


            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            Mock <ITelemetryKeyCache> keyCacheMock = new Mock <ITelemetryKeyCache>();

            keyCacheMock.Setup(c => c.GetProcessedKey(It.IsAny <string>())).Returns <string>(input => input);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(
                envFactoryMock.Object,
                GetOptions(TimeSpan.FromSeconds(1)),
                SDKVersionUtils.Instance,
                keyCacheMock.Object);
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);

            ISupportProperties telemetryWithProperties = telemetry as ISupportProperties;

            Assert.Equal("Cid", telemetryWithProperties.Properties["Kubernetes.Container.ID"]);
            Assert.Equal("CName", telemetryWithProperties.Properties["Kubernetes.Container.Name"]);

            Assert.Equal("Pid", telemetryWithProperties.Properties["Kubernetes.Pod.ID"]);
            Assert.Equal("PName", telemetryWithProperties.Properties["Kubernetes.Pod.Name"]);
            Assert.Equal("PLabels", telemetryWithProperties.Properties["Kubernetes.Pod.Labels"]);
            Assert.Equal("PNS", telemetryWithProperties.Properties["Kubernetes.Pod.Namespace"]);

            Assert.Equal("RName", telemetryWithProperties.Properties["Kubernetes.ReplicaSet.Name"]);

            Assert.Equal("DName", telemetryWithProperties.Properties["Kubernetes.Deployment.Name"]);

            Assert.Equal("Nid", telemetryWithProperties.Properties["Kubernetes.Node.ID"]);
            Assert.Equal("NName", telemetryWithProperties.Properties["Kubernetes.Node.Name"]);
        }
Beispiel #9
0
        public void InitializeSetsRoleName()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");
            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(null, envMock.Object);
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);

            Assert.Equal("Hello RoleName", telemetry.Context.Cloud.RoleName);
        }
        public void InitializeShouldNotOverwriteExistingRoleName()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("New RoleName");
            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envMock.Object, GetLogger());
            ITelemetry telemetry = new TraceTelemetry();

            telemetry.Context.Cloud.RoleName = "Existing RoleName";
            target.Initialize(telemetry);

            Assert.Equal("Existing RoleName", telemetry.Context.Cloud.RoleName);
        }
Beispiel #11
0
        public void ConstructorSetK8sEnvironment()
        {
            var envMock     = new Mock <IK8sEnvironment>();
            var factoryMock = new Mock <IK8sEnvironmentFactory>();

            factoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(factoryMock.Object, TimeSpan.FromSeconds(1), SDKVersionUtils.Instance, GetLogger());

            Assert.NotNull(target._k8sEnvironment);
            Assert.Equal(factoryMock.Object, target._k8sEnvFactory);
            Assert.Equal(envMock.Object, target._k8sEnvironment);
        }
        public void InitializeSetsCustomDimensions()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            envMock.Setup(env => env.ContainerName).Returns("CName");
            envMock.Setup(env => env.PodID).Returns("Pid");
            envMock.Setup(env => env.PodName).Returns("PName");
            envMock.Setup(env => env.PodLabels).Returns("PLabels");
            envMock.Setup(env => env.ReplicaSetUid).Returns("Rid");
            envMock.Setup(env => env.ReplicaSetName).Returns("RName");
            envMock.Setup(env => env.DeploymentUid).Returns("Did");
            envMock.Setup(env => env.DeploymentName).Returns("DName");
            envMock.Setup(env => env.NodeUid).Returns("Nid");
            envMock.Setup(env => env.NodeName).Returns("NName");

            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(
                envFactoryMock.Object,
                GetOptions(TimeSpan.FromSeconds(1)),
                SDKVersionUtils.Instance);
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);

            ISupportProperties telemetryWithProperties = telemetry as ISupportProperties;

            Assert.Equal("Cid", telemetryWithProperties.Properties["Kubernetes.Container.ID"]);
            Assert.Equal("CName", telemetryWithProperties.Properties["Kubernetes.Container.Name"]);

            Assert.Equal("Pid", telemetryWithProperties.Properties["Kubernetes.Pod.ID"]);
            Assert.Equal("PName", telemetryWithProperties.Properties["Kubernetes.Pod.Name"]);
            Assert.Equal("PLabels", telemetryWithProperties.Properties["Kubernetes.Pod.Labels"]);

            Assert.Equal("RName", telemetryWithProperties.Properties["Kubernetes.ReplicaSet.Name"]);

            Assert.Equal("DName", telemetryWithProperties.Properties["Kubernetes.Deployment.Name"]);

            Assert.Equal("Nid", telemetryWithProperties.Properties["Kubernetes.Node.ID"]);
            Assert.Equal("NName", telemetryWithProperties.Properties["Kubernetes.Node.Name"]);

#if !NETSTANDARD1_3 && !NETSTANDARD1_6
            Assert.NotNull(telemetryWithProperties.Properties["Process.CPU(%)"]);
            Assert.NotNull(telemetryWithProperties.Properties["Process.Memory"]);
#endif
        }
Beispiel #13
0
        public void SlowK8sEnvironmentBuildWillNotBlockTelemetryInitializerConstructor()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(envMock.Object, TimeSpan.FromMinutes(1));
            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envFactoryMock.Object, TimeSpan.FromSeconds(30), SDKVersionUtils.Instance, GetLogger());

            // K8s Enviornment is still null.
            Assert.Null(target._k8sEnvironment);
            // And is not yet timed out.
            Assert.False(target._isK8sQueryTimeout);
        }
Beispiel #14
0
        public void ConstructorSetsNullGetsNull()
        {
            Exception ex = Assert.Throws <ArgumentNullException>(() =>
            {
                Mock <ITelemetryKeyCache> keyCacheMock = new Mock <ITelemetryKeyCache>();
                KubernetesTelemetryInitializer target  = new KubernetesTelemetryInitializer(
                    null,
                    GetOptions(TimeSpan.FromSeconds(1)),
                    SDKVersionUtils.Instance,
                    keyCacheMock.Object
                    );
            });

            Assert.Equal("Value cannot be null.\r\nParameter name: k8sEnvFactory", ex.Message);
        }
Beispiel #15
0
        public async Task QueryK8sEnvironmentWillTimeout()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(envMock.Object, TimeSpan.FromMinutes(1));
            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envFactoryMock.Object, TimeSpan.FromSeconds(1), SDKVersionUtils.Instance, GetLogger());

            Assert.False(target._isK8sQueryTimeout);
            await Task.Delay(TimeSpan.FromSeconds(1));

            Assert.True(target._isK8sQueryTimeout);
        }
Beispiel #16
0
        public void InitializeSetsRoleName()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");
            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envFactoryMock.Object, TimeSpan.FromSeconds(1), SDKVersionUtils.Instance, GetLogger());
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);

            Assert.Equal("Hello RoleName", telemetry.Context.Cloud.RoleName);
        }
Beispiel #17
0
        public void InitializeWillNotOverwriteExistingCustomDimension()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");

            envMock.Setup(env => env.ContainerID).Returns("Cid");

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(null, envMock.Object);
            ITelemetry telemetry = new TraceTelemetry();

            telemetry.Context.Properties["K8s.Container.ID"] = "Existing Cid";
            target.Initialize(telemetry);

            Assert.Equal("Existing Cid", telemetry.Context.Properties["K8s.Container.ID"]);
        }
Beispiel #18
0
        public void TimeoutGettingK8sEnvNoException()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(envMock.Object, TimeSpan.FromMinutes(1));
            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envFactoryMock.Object, TimeSpan.FromSeconds(1), SDKVersionUtils.Instance, GetLogger());

            ITelemetry telemetry = new TraceTelemetry();

            telemetry.Context.Properties["K8s.Container.ID"] = "No Crash";
            target.Initialize(telemetry);

            Assert.Equal("No Crash", telemetry.Context.Properties["K8s.Container.ID"]);
        }
Beispiel #19
0
        public void InitializeWithEmptyForOptionalPropertyDoesNotLogError()
        {
            var listener = new TestDiagnosticSourceObserver();

            ApplicationInsightsKubernetesDiagnosticSource.Instance.Observable.SubscribeWithAdapter(listener);

            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            envMock.Setup(env => env.ContainerName).Returns("CName");
            envMock.Setup(env => env.PodID).Returns("Pid");
            envMock.Setup(env => env.PodName).Returns("PName");
            envMock.Setup(env => env.PodLabels).Returns("PLabels");

            // The following properties are optional.
            envMock.Setup(env => env.ReplicaSetUid).Returns <string>(null);
            envMock.Setup(env => env.ReplicaSetName).Returns <string>(null);
            envMock.Setup(env => env.DeploymentUid).Returns <string>(null);
            envMock.Setup(env => env.DeploymentName).Returns <string>(null);
            envMock.Setup(env => env.PodNamespace).Returns <string>(null);
            envMock.Setup(env => env.NodeUid).Returns("Nid");
            envMock.Setup(env => env.NodeName).Returns("NName");

            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            Mock <ITelemetryKeyCache> keyCacheMock = new Mock <ITelemetryKeyCache>();

            keyCacheMock.Setup(c => c.GetProcessedKey(It.IsAny <string>())).Returns <string>(input => input);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(
                envFactoryMock.Object,
                GetOptions(TimeSpan.FromSeconds(1)),
                SDKVersionUtils.Instance,
                keyCacheMock.Object);
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);

            Assert.Equal(0, listener.GetCount(DiagnosticLogLevel.Error));
        }
Beispiel #20
0
        public void InitializeWillNotOverwriteExistingCustomDimension()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");
            envMock.Setup(env => env.ContainerID).Returns("Cid");

            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envFactoryMock.Object, TimeSpan.FromSeconds(1), SDKVersionUtils.Instance, GetLogger());
            ITelemetry telemetry = new TraceTelemetry();

            telemetry.Context.Properties["K8s.Container.ID"] = "Existing Cid";
            target.Initialize(telemetry);

            Assert.Equal("Existing Cid", telemetry.Context.Properties["K8s.Container.ID"]);
        }
        /// <summary>
        /// Enable applicaiton insights for kubernetes.
        /// </summary>
        /// <param name="loggerFactory"></param>
        /// <param name="timeout"></param>
        public static void EnableKubernetes(TelemetryConfiguration configuration, ILoggerFactory loggerFactory = null, TimeSpan?timeout = null)
        {
            // 2 minutes maximum to spin up the container.
            timeout = timeout ?? TimeSpan.FromMinutes(2);

            ILogger logger = loggerFactory?.CreateLogger("K8sEnvInitializer");

            Task.Run(() =>
            {
                try
                {
                    string versionInfo = typeof(ApplicationInsightsExtensions).GetTypeInfo().Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;
                    logger?.LogInformation(Invariant($"ApplicationInsights.Kubernetes.Version:{versionInfo}"));
                }
                catch (Exception ex)
                {
                    logger?.LogError("Failed to fetch ApplicaitonInsights.Kubernetes' version info. Details" + ex.ToString());
                }
            });

            try
            {
                K8sEnvironment k8sEnv = K8sEnvironment.CreateAsync(timeout.Value, loggerFactory).ConfigureAwait(false).GetAwaiter().GetResult();
                if (k8sEnv != null)
                {
                    // Wait until the initialization is done.
                    k8sEnv.InitializationWaiter.WaitOne(TimeSpan.FromMinutes(1));

                    // Inject the telemetry initializer.
                    ITelemetryInitializer initializer = new KubernetesTelemetryInitializer(loggerFactory, k8sEnv);
                    configuration.TelemetryInitializers.Add(initializer);
                    logger?.LogDebug("Application Insights Kubernetes injected the service successfully.");
                }
                else
                {
                    logger?.LogError("Application Insights Kubernetes failed to start.");
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex.ToString());
            }
        }
Beispiel #22
0
        /// <summary>
        /// Enable applicaiton insights for kubernetes.
        /// </summary>
        /// <param name="loggerFactory"></param>
        /// <param name="timeout"></param>
        public static void EnableKubernetes(IServiceCollection serviceCollection, TelemetryConfiguration configuration, TimeSpan?timeout = null)
        {
            // 2 minutes maximum to spin up the container.
            timeout = timeout ?? TimeSpan.FromMinutes(2);

            serviceCollection = BuildK8sServiceCollection(serviceCollection);
            IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
            ILogger          logger          = serviceProvider.GetService <ILogger <KubernetesModule> >();

            Task.Run(() =>
            {
                try
                {
                    string versionInfo = typeof(ApplicationInsightsExtensions).GetTypeInfo().Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;
                    logger.LogInformation(Invariant($"ApplicationInsights.Kubernetes.Version:{versionInfo}"));
                }
                catch (Exception ex)
                {
                    logger.LogError("Failed to fetch ApplicaitonInsights.Kubernetes' version info. Details" + ex.ToString());
                }
            });

            try
            {
                K8sEnvironment k8sEnv = serviceProvider.GetRequiredService <K8sEnvironmentFactory>().CreateAsync(timeout.Value).ConfigureAwait(false).GetAwaiter().GetResult();
                if (k8sEnv != null)
                {
                    // Inject the telemetry initializer.
                    ITelemetryInitializer initializer = new KubernetesTelemetryInitializer(k8sEnv, serviceProvider.GetService <ILogger <KubernetesTelemetryInitializer> >());
                    configuration.TelemetryInitializers.Add(initializer);
                    logger?.LogDebug("Application Insights Kubernetes injected the service successfully.");
                }
                else
                {
                    logger?.LogError("Application Insights Kubernetes failed to start.");
                }
                isInitialized = true;
            }
            catch (Exception ex)
            {
                logger?.LogError(ex.ToString());
            }
        }
        public void InitializeSetsCustomDimensions()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");

            envMock.Setup(env => env.ContainerID).Returns("Cid");
            envMock.Setup(env => env.ContainerName).Returns("CName");
            envMock.Setup(env => env.PodID).Returns("Pid");
            envMock.Setup(env => env.PodName).Returns("PName");
            envMock.Setup(env => env.PodLabels).Returns("PLabels");
            envMock.Setup(env => env.ReplicaSetUid).Returns("Rid");
            envMock.Setup(env => env.ReplicaSetName).Returns("RName");
            envMock.Setup(env => env.DeploymentUid).Returns("Did");
            envMock.Setup(env => env.DeploymentName).Returns("DName");
            envMock.Setup(env => env.NodeUid).Returns("Nid");
            envMock.Setup(env => env.NodeName).Returns("NName");

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envMock.Object, GetLogger());
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);

            Assert.Equal("Cid", telemetry.Context.Properties["Kubernetes.Container.ID"]);
            Assert.Equal("CName", telemetry.Context.Properties["Kubernetes.Container.Name"]);

            Assert.Equal("Pid", telemetry.Context.Properties["Kubernetes.Pod.ID"]);
            Assert.Equal("PName", telemetry.Context.Properties["Kubernetes.Pod.Name"]);
            Assert.Equal("PLabels", telemetry.Context.Properties["Kubernetes.Pod.Labels"]);

            Assert.Equal("RName", telemetry.Context.Properties["Kubernetes.ReplicaSet.Name"]);

            Assert.Equal("DName", telemetry.Context.Properties["Kubernetes.Deployment.Name"]);

            Assert.Equal("Nid", telemetry.Context.Properties["Kubernetes.Node.ID"]);
            Assert.Equal("NName", telemetry.Context.Properties["Kubernetes.Node.Name"]);

#if !NETSTANDARD1_3 && !NETSTANDARD1_6
            Assert.NotNull(telemetry.Context.Properties["Process.CPU(%)"]);
            Assert.NotNull(telemetry.Context.Properties["Process.Memory"]);
#endif
        }
Beispiel #24
0
        public void InitializeSetsRoleName()
        {
            var envMock = new Mock <IK8sEnvironment>();

            envMock.Setup(env => env.ContainerName).Returns("Hello RoleName");
            var envFactoryMock = new Mock <IK8sEnvironmentFactory>();

            envFactoryMock.Setup(f => f.CreateAsync(It.IsAny <DateTime>())).ReturnsAsync(() => envMock.Object);
            Mock <ITelemetryKeyCache> keyCacheMock = new Mock <ITelemetryKeyCache>();

            keyCacheMock.Setup(c => c.GetProcessedKey(It.IsAny <string>())).Returns <string>(input => input);

            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(envFactoryMock.Object,
                                                                                       GetOptions(TimeSpan.FromSeconds(1)),
                                                                                       SDKVersionUtils.Instance,
                                                                                       keyCacheMock.Object);
            ITelemetry telemetry = new TraceTelemetry();

            target.Initialize(telemetry);

            Assert.Equal("Hello RoleName", telemetry.Context.Cloud.RoleName);
        }
Beispiel #25
0
        public void ConstructorSetsNullGetsNull()
        {
            KubernetesTelemetryInitializer target = new KubernetesTelemetryInitializer(null, null);

            Assert.Null(target.K8sEnvironment);
        }