示例#1
0
 protected TelemetryProvider(AzurePSDataCollectionProfile profile, MetricHelper helper, Action <string> warningLogger, Action <string> debugLogger)
 {
     _dataCollectionProfile = profile;
     _helper        = helper;
     _warningLogger = warningLogger;
     _debugLogger   = debugLogger;
 }
示例#2
0
        /// <summary>
        /// Cmdlet begin process. Write to logs, setup Http Tracing and initialize profile
        /// </summary>
        protected override void BeginProcessing()
        {
            FlushInitializationWarnings();
            SessionState = base.SessionState;
            var profile = _dataCollectionProfile;

            //TODO: Inject from CI server
            lock (lockObject)
            {
                if (_metricHelper == null)
                {
                    _metricHelper = new MetricHelper(profile);
                    _metricHelper.AddTelemetryClient(new TelemetryClient
                    {
                        InstrumentationKey = "7df6ff70-8353-4672-80d6-568517fed090"
                    });
                }
            }

            InitializeQosEvent();
            LogCmdletStartInvocationInfo();
            InitDebuggingFilter();
            SetupDebuggingTraces();
            SetupHttpClientPipeline();
            base.BeginProcessing();

            //Now see if the cmdlet has any Breaking change attributes on it and process them if it does
            //This will print any breaking change attribute messages that are applied to the cmdlet
            BreakingChangeAttributeHelper.ProcessCustomAttributesAtRuntime(this.GetType(), this.MyInvocation, WriteWarning);
            PreviewAttributeHelper.ProcessCustomAttributesAtRuntime(this.GetType(), this.MyInvocation, WriteDebug);
        }
示例#3
0
        public void ValidateMetricTelemetryItem()
        {
            var metrics = new List <Metric>();

            using var meter    = new Meter(nameof(ValidateMetricTelemetryItem));
            using var provider = Sdk.CreateMeterProviderBuilder()
                                 .AddMeter(meter.Name)
                                 .AddInMemoryExporter(metrics)
                                 .Build();

            var doubleCounter = meter.CreateCounter <double>("TestDoubleCounter");

            doubleCounter.Add(123.45);
            provider.ForceFlush();

            var telemetryItems = MetricHelper.OtelToAzureMonitorMetrics(new Batch <Metric>(metrics.ToArray(), 1), "testRoleName", "testRoleInstance", "00000000-0000-0000-0000-000000000000");

            Assert.Single(telemetryItems);
            Assert.Equal("MetricData", telemetryItems[0].Data.BaseType);
            Assert.Equal("00000000-0000-0000-0000-000000000000", telemetryItems[0].InstrumentationKey);
            Assert.Equal("testRoleName", telemetryItems[0].Tags[ContextTagKeys.AiCloudRole.ToString()]);
            Assert.Equal("testRoleInstance", telemetryItems[0].Tags[ContextTagKeys.AiCloudRoleInstance.ToString()]);

            var metricsData = (MetricsData)telemetryItems[0].Data.BaseData;

            Assert.Equal(2, metricsData.Version);
            Assert.Equal("TestDoubleCounter", metricsData.Metrics.First().Name);
            Assert.Equal(123.45, metricsData.Metrics.First().Value);
            Assert.Equal(DataPointType.Aggregation, metricsData.Metrics.First().DataPointType);
            Assert.Equal(1, metricsData.Properties.Count);
            Assert.Equal("60000", metricsData.Properties["_MS.AggregationIntervalMs"]);
        }
示例#4
0
        /// <summary>
        /// Invoke this method when the cmdlet is completed or terminated.
        /// </summary>
        protected void LogQosEvent(bool waitForMetricSending = false)
        {
            if (QosEvent == null)
            {
                return;
            }

            QosEvent.FinishQosEvent();

            if (!IsUsageMetricEnabled && (!IsErrorMetricEnabled || QosEvent.IsSuccess))
            {
                return;
            }

            if (!IsDataCollectionAllowed())
            {
                return;
            }

            WriteDebug(QosEvent.ToString());

            try
            {
                MetricHelper.LogQoSEvent(QosEvent, IsUsageMetricEnabled, IsErrorMetricEnabled);
                MetricHelper.FlushMetric(waitForMetricSending);
                WriteDebug("Finish sending metric.");
            }
            catch (Exception e)
            {
                //Swallow error from Application Insights event collection.
                WriteWarning(e.ToString());
            }
        }
        public void CanSerializeSimpleFeedbackPayloadIntoProperForm()
        {
            var payload = new PSAzureFeedback
            {
                ModuleName       = "Module",
                ModuleVersion    = "1.0.0",
                SubscriptionId   = Guid.NewGuid().ToString(),
                TenantId         = Guid.NewGuid().ToString(),
                Environment      = "AzureCloud",
                Recommendation   = 10,
                PositiveComments = "Positive",
                NegativeComments = "Negative",
                Email            = "*****@*****.**"
            };

            var serializedPayload = MetricHelper.SerializeCustomEventPayload(payload);

            Assert.Equal(payload.ModuleName, serializedPayload["moduleName"]);
            Assert.Equal(payload.ModuleVersion, serializedPayload["moduleVersion"]);
            Assert.Equal(payload.SubscriptionId.ToString(), serializedPayload["subscriptionId"]);
            Assert.Equal(payload.TenantId.ToString(), serializedPayload["tenantId"]);
            Assert.Equal(payload.Environment, serializedPayload["environment"]);
            Assert.Equal(payload.Recommendation.ToString(), serializedPayload["recommendation"]);
            Assert.Equal(payload.PositiveComments, serializedPayload["positiveComments"]);
            Assert.Equal(payload.NegativeComments, serializedPayload["negativeComments"]);
            Assert.Equal(payload.Email, serializedPayload["email"]);
        }
示例#6
0
 /// <summary>
 /// Perform end of pipeline processing.
 /// </summary>
 protected override void EndProcessing()
 {
     if (this.MyInvocation?.MyCommand?.Version != null && SurveyHelper.GetInstance().ShouldPropmtSurvey(this.MyInvocation.MyCommand.ModuleName, this.MyInvocation.MyCommand.Version))
     {
         WriteSurvey();
         if (_qosEvent != null)
         {
             _qosEvent.SurveyPrompted = true;
         }
     }
     if (MetricHelper.IsCalledByUser())
     {
         // Send telemetry when cmdlet is directly called by user
         LogQosEvent();
     }
     else
     {
         // When cmdlet is called within another cmdlet, we will not add a new telemetry, but add the cmdlet name to InternalCalledCmdlets
         MetricHelper.AppendInternalCalledCmdlet(this.MyInvocation?.MyCommand?.Name);
     }
     LogCmdletEndInvocationInfo();
     TearDownDebuggingTraces();
     TearDownHttpClientPipeline();
     _previousEndTime = DateTimeOffset.Now;
     base.EndProcessing();
 }
示例#7
0
        protected override void InitializeQosEvent()
        {
            var commandAlias = this.GetType().Name;

            if (this.MyInvocation != null && this.MyInvocation.MyCommand != null)
            {
                commandAlias = this.MyInvocation.MyCommand.Name;
            }

            _qosEvent = new AzurePSQoSEvent()
            {
                CommandName      = commandAlias,
                ModuleName       = this.GetType().Assembly.GetName().Name,
                ModuleVersion    = this.GetType().Assembly.GetName().Version.ToString(),
                ClientRequestId  = this._clientRequestId,
                SessionId        = _sessionId,
                IsSuccess        = true,
                ParameterSetName = this.ParameterSetName
            };

            if (AzVersion == null)
            {
                AzVersion = this.LoadAzVersion();
                UserAgent = new ProductInfoHeaderValue("AzurePowershell", string.Format("Az{0}", AzVersion)).ToString();
                string hostEnv = Environment.GetEnvironmentVariable("AZUREPS_HOST_ENVIRONMENT");
                if (!String.IsNullOrWhiteSpace(hostEnv))
                {
                    UserAgent += string.Format(";{0}", hostEnv.Trim());
                }
            }
            _qosEvent.AzVersion = AzVersion;
            _qosEvent.UserAgent = UserAgent;

            if (this.MyInvocation != null && !string.IsNullOrWhiteSpace(this.MyInvocation.InvocationName))
            {
                _qosEvent.InvocationName = this.MyInvocation.InvocationName;
            }

            if (this.MyInvocation != null && this.MyInvocation.BoundParameters != null &&
                this.MyInvocation.BoundParameters.Keys != null)
            {
                _qosEvent.Parameters = string.Join(" ",
                                                   this.MyInvocation.BoundParameters.Keys.Select(
                                                       s => string.Format(CultureInfo.InvariantCulture, "-{0} ***", s)));
            }

            IAzureContext context;

            _qosEvent.Uid = "defaultid";
            if (TryGetDefaultContext(out context))
            {
                _qosEvent.SubscriptionId = context.Subscription?.Id;
                _qosEvent.TenantId       = context.Tenant?.Id;
                if (context.Account != null && !String.IsNullOrWhiteSpace(context.Account.Id))
                {
                    _qosEvent.Uid = MetricHelper.GenerateSha256HashString(context.Account.Id.ToString());
                }
            }
        }
        public void MetricHelperShouldParseMi()
        {
            var result = MetricHelper.ParseMemoryUnit("656Mi");

            Assert.AreEqual(result.Value, 656);
            Assert.AreEqual(result.BaseValue, 687865856);
            Assert.AreEqual(result.Unit, "Mi");
        }
        public void MetricHelperShouldParseMillicores()
        {
            var result = MetricHelper.ParseCPUUnit("62662558m");

            Assert.AreEqual(result.Value, 62662558);
            Assert.AreEqual(result.BaseValue, 626625580);
            Assert.AreEqual(result.Unit, "Millicores");
        }
        public void MetricHelperShouldParseKi()
        {
            var result = MetricHelper.ParseMemoryUnit("673584Ki");

            Assert.AreEqual(result.Value, 673584);
            Assert.AreEqual(result.BaseValue, 689750016);
            Assert.AreEqual(result.Unit, "Ki");
        }
示例#11
0
        public void HashOfValidValueSucceeds()
        {
            string inputValue = "Sample value to hash of suitable length and complexity.";
            var    hash       = MetricHelper.GenerateSha256HashString(inputValue);

            Assert.NotNull(hash);
            Assert.True(hash.Length > 0);
            Assert.NotEqual <string>(inputValue, hash, StringComparer.OrdinalIgnoreCase);
        }
示例#12
0
        public IOrderedQueryable <Metric> GetLatestBySensorId(Guid sensorId, string property)
        {
            var oneDayBefore = DateTime.UtcNow.AddDays(-1);

            return(Context.Set <Metric>()
                   .Where(sd => sd.SensorId == sensorId && sd.Date >= oneDayBefore)
                   .Where(MetricHelper.GetNotNullPropertyExpression(property))
                   .OrderBy(sd => sd.Date));
        }
示例#13
0
        /// <summary>
        /// Initializes AzurePSCmdlet properties.
        /// </summary>
        public AzurePSCmdlet()
        {
            DebugMessages = new ConcurrentQueue <string>();

            //TODO: Inject from CI server
            _metricHelper = new MetricHelper();
            _metricHelper.AddTelemetryClient(new TelemetryClient
            {
                InstrumentationKey = "7df6ff70-8353-4672-80d6-568517fed090"
            });
        }
示例#14
0
            public TestClassResult(IEnumerable <Run> runs, MetricHelper metricHelper, string[] frameworkMap)
            {
                TestClassName = runs.Select(run => run.TestClass).Distinct().Single();

                foreach (var variationRuns in runs
                         .GroupBy(@class => new { @class.TestMethod, @class.Variation })
                         .OrderBy(grouping => grouping.Key.TestMethod + grouping.Key.Variation))
                {
                    _results.Add(new TestVariationResult(variationRuns, metricHelper, frameworkMap));
                }
            }
示例#15
0
            public FrameworkResult(IEnumerable <Run> runs, MetricHelper metricHelper)
            {
                var defaultRuns = runs.Where(run => run.ProductReportingVersion == "Default");

                var result = defaultRuns.Any() ? (double?)defaultRuns.Average(run => metricHelper.GetMetric(run)) : null;

                if (result != null)
                {
                    Result = metricHelper.DisplayMetric(result.Value);
                }
            }
示例#16
0
        private static MetricHelper CreateMetricHelper(AzurePSDataCollectionProfile profile)
        {
            var result = new MetricHelper(profile);

            result.AddTelemetryClient(new TelemetryClient
            {
                InstrumentationKey = "7df6ff70-8353-4672-80d6-568517fed090"
            });

            return(result);
        }
示例#17
0
            public TestVariationResult(IEnumerable <Run> runs, MetricHelper metricHelper, string[] frameworkMap)
            {
                TestMethodName = runs.Select(run => run.TestMethod).Distinct().Single();
                VariationName  = runs.Select(run => run.Variation).Distinct().Single();

                _results = new FrameworkResult[frameworkMap.Length];
                for (int i = 0; i < frameworkMap.Length; i++)
                {
                    var frameworkRuns = runs.Where(variation => variation.Framework == frameworkMap[i]);
                    _results[i] = new FrameworkResult(frameworkRuns, metricHelper);
                }
            }
示例#18
0
        public SensorDataListModel GetSensorData(Guid sensorId, string property)
        {
            var sensorMetrics = Repository.GetLatestBySensorId(sensorId, property);

            return(new SensorDataListModel()
            {
                SensorId = sensorId,
                DataList = sensorMetrics
                           .Select(MetricHelper.GetPropertyExpression(property))
                           .ToList()
                           .ConvertAll(NumberExtensions.ParseDoubleValue),
                Dates = sensorMetrics.Select(sm => sm.Date).ToList()
            });
        }
示例#19
0
        public IndexViewModel(IEnumerable <Run> runs, int days, Metrics metric)
        {
            _frameworks = runs
                          .Select(run => run.Framework)
                          .Distinct()
                          .OrderBy(framework => framework)
                          .ToArray();

            Days   = days;
            Metric = metric;

            foreach (var testClassRuns in runs.GroupBy(run => run.TestClass).OrderBy(grouping => grouping.Key))
            {
                _results.Add(new TestClassResult(testClassRuns, MetricHelper.Create(metric), _frameworks));
            }
        }
示例#20
0
        protected override void InitializeQosEvent()
        {
            var commandAlias = this.GetType().Name;

            if (this.MyInvocation != null && this.MyInvocation.MyCommand != null)
            {
                commandAlias = this.MyInvocation.MyCommand.Name;
            }

            _qosEvent = new AzurePSQoSEvent()
            {
                CommandName      = commandAlias,
                ModuleName       = this.GetType().Assembly.GetName().Name,
                ModuleVersion    = this.GetType().Assembly.GetName().Version.ToString(),
                ClientRequestId  = this._clientRequestId,
                SessionId        = _sessionId,
                IsSuccess        = true,
                ParameterSetName = this.ParameterSetName
            };

            if (this.MyInvocation != null && !string.IsNullOrWhiteSpace(this.MyInvocation.InvocationName))
            {
                _qosEvent.InvocationName = this.MyInvocation.InvocationName;
            }

            if (this.MyInvocation != null && this.MyInvocation.BoundParameters != null &&
                this.MyInvocation.BoundParameters.Keys != null)
            {
                _qosEvent.Parameters = string.Join(" ",
                                                   this.MyInvocation.BoundParameters.Keys.Select(
                                                       s => string.Format(CultureInfo.InvariantCulture, "-{0} ***", s)));
            }

            IAzureContext context;

            if (TryGetDefaultContext(out context) &&
                context.Account != null &&
                !string.IsNullOrWhiteSpace(context.Account.Id))
            {
                _qosEvent.Uid = MetricHelper.GenerateSha256HashString(context.Account.Id.ToString());
            }
            else
            {
                _qosEvent.Uid = "defaultid";
            }
        }
        protected override void InitializeQosEvent()
        {
            base.InitializeQosEvent();

            IAzureContext context;

            _qosEvent.Uid = "defaultid";
            if (RequireDefaultContext() && TryGetDefaultContext(out context))
            {
                _qosEvent.SubscriptionId = context.Subscription?.Id;
                _qosEvent.TenantId       = context.Tenant?.Id;
                if (context.Account != null && !String.IsNullOrWhiteSpace(context.Account.Id))
                {
                    _qosEvent.Uid = MetricHelper.GenerateSha256HashString(context.Account.Id.ToString());
                }
            }
        }
示例#22
0
        /// <summary>
        /// Cmdlet begin process. Write to logs, setup Http Tracing and initialize profile
        /// </summary>
        protected override void BeginProcessing()
        {
            FlushInitializationWarnings();
            SessionState = base.SessionState;
            var profile = _dataCollectionProfile;

            //TODO: Inject from CI server
            if (_metricHelper == null)
            {
                lock (lockObject)
                {
                    if (_metricHelper == null)
                    {
                        _metricHelper = new MetricHelper(profile);
                        _metricHelper.AddDefaultTelemetryClient();
                    }
                }
            }

            // Fetch module name and version which will be used by telemetry and useragent
            if (this.MyInvocation != null && this.MyInvocation.MyCommand != null)
            {
                this.ModuleName = this.MyInvocation.MyCommand.ModuleName;
                if (this.MyInvocation.MyCommand.Version != null)
                {
                    this.ModuleVersion = this.MyInvocation.MyCommand.Version.ToString();
                }
            }
            else
            {
                this.ModuleName    = this.GetType().Assembly.GetName().Name;
                this.ModuleVersion = this.GetType().Assembly.GetName().Version.ToString();
            }

            InitializeQosEvent();
            LogCmdletStartInvocationInfo();
            InitDebuggingFilter();
            SetupDebuggingTraces();
            SetupHttpClientPipeline();
            base.BeginProcessing();

            //Now see if the cmdlet has any Breaking change attributes on it and process them if it does
            //This will print any breaking change attribute messages that are applied to the cmdlet
            BreakingChangeAttributeHelper.ProcessCustomAttributesAtRuntime(this.GetType(), this.MyInvocation, WriteWarning);
            PreviewAttributeHelper.ProcessCustomAttributesAtRuntime(this.GetType(), this.MyInvocation, WriteDebug);
        }
示例#23
0
        protected void InitializeQosEvent()
        {
            QosEvent = new AzurePSQoSEvent()
            {
                CmdletType = this.GetType().Name,
                IsSuccess  = true,
            };

            if (this.Profile != null && this.Profile.DefaultSubscription != null)
            {
                QosEvent.Uid = MetricHelper.GenerateSha256HashString(
                    this.Profile.DefaultSubscription.Id.ToString());
            }
            else
            {
                QosEvent.Uid = "defaultid";
            }
        }
示例#24
0
        public void HashMacAddressOnThrowIsNull()
        {
            Mock <INetworkHelper> helper = new Mock <INetworkHelper>();

            helper.Setup((f) => f.GetMACAddress()).Throws(new InvalidOperationException("This exception should be handled"));
            var metricHelper = new MetricHelper(helper.Object);

            metricHelper.HashMacAddress = string.Empty;
            try
            {
                Assert.Null(metricHelper.HashMacAddress);
                Assert.Null(metricHelper.HashMacAddress);
                helper.Verify((f) => f.GetMACAddress(), Times.Once);
            }
            finally
            {
                metricHelper.HashMacAddress = string.Empty;
            }
        }
示例#25
0
        public void HashofEmptyNetworkMACAddressIsNull()
        {
            Mock <INetworkHelper> helper = new Mock <INetworkHelper>();

            helper.Setup((f) => f.GetMACAddress()).Returns(string.Empty);
            var metricHelper = new MetricHelper(helper.Object);

            metricHelper.HashMacAddress = string.Empty;
            try
            {
                Assert.Null(metricHelper.HashMacAddress);
                Assert.Null(metricHelper.HashMacAddress);
                helper.Verify((f) => f.GetMACAddress(), Times.Once);
            }
            finally
            {
                metricHelper.HashMacAddress = string.Empty;
            }
        }
        public async Task Handle(MetricQueryRequest <NodeRamUsageWidget> request, CancellationToken cancellationToken)
        {
            var nodeCPUUsageWidget = request.DataContext;

            var client = kubernetesHelper.GetKubernetesClient(nodeCPUUsageWidget);

            var metricsResponse = await client.GetNodeMetricsAsync(nodeCPUUsageWidget.NodeName, cancellationToken);

            if (metricsResponse.IsValid)
            {
                var metric = MetricHelper.ParseMemoryUnit(metricsResponse.Usage.Memory);
                request.DataContext.Value = metric.BaseValue;
                request.DataContext.State = State.Ok;
            }
            else
            {
                nodeCPUUsageWidget.State = State.Invalid;
            }
        }
示例#27
0
 public void Add(MetricDTO metric)
 {
     if (string.IsNullOrEmpty(Setup.GetAPIKey()))
     {
         _metricRepository.Add(new Entities.Metric()
         {
             ApplicationName = metric.ApplicationName, Duration = metric.Duration, MetricName = metric.MetricName
         });
         _metricRepository.UnitOfWork.Commit();
     }
     else
     {
         using (var metricHelper = new MetricHelper(Guid.Parse(Setup.GetAPIKey())))
         {
             metricHelper.Add(new Entities.Metric()
             {
                 ApplicationName = metric.ApplicationName, Duration = metric.Duration, MetricName = metric.MetricName
             });
         }
     }
 }
示例#28
0
        public void HashofNullNetworkMACAddressIsNull()
        {
            Mock <INetworkHelper> helper = new Mock <INetworkHelper>();

            helper.Setup((f) => f.GetMACAddress()).Returns(() => null);
            var metricHelper = new MetricHelper(helper.Object);

            metricHelper.HashMacAddress = string.Empty;
            try
            {
                // verify that initialization happens only once and
                // there are no issues with retrieving the value
                Assert.Null(metricHelper.HashMacAddress);
                Assert.Null(metricHelper.HashMacAddress);
                helper.Verify((f) => f.GetMACAddress(), Times.Once);
            }
            finally
            {
                metricHelper.HashMacAddress = string.Empty;
            }
        }
示例#29
0
 public void AddRange(List <MetricDTO> metrics)
 {
     if (string.IsNullOrEmpty(Setup.GetAPIKey()))
     {
         _metricRepository.AddRange(metrics.Select(x => new Entities.Metric()
         {
             ApplicationName = x.ApplicationName, Duration = x.Duration, MetricName = x.MetricName
         }));
         _metricRepository.UnitOfWork.Commit();
     }
     else
     {
         //Call Metricity API Helper
         using (var metricHelper = new MetricHelper(Guid.Parse(Setup.GetAPIKey())))
         {
             metricHelper.AddRange(metrics.Select(x => new Entities.Metric()
             {
                 ApplicationName = x.ApplicationName, Duration = x.Duration, MetricName = x.MetricName
             }));
         }
     }
 }
示例#30
0
        protected override void InitializeQosEvent()
        {
            var commandAlias = this.GetType().Name;

            if (this.MyInvocation != null && this.MyInvocation.MyCommand != null)
            {
                commandAlias = this.MyInvocation.MyCommand.Name;
            }

            QosEvent = new AzurePSQoSEvent()
            {
                CommandName     = commandAlias,
                ModuleName      = this.GetType().Assembly.GetName().Name,
                ModuleVersion   = this.GetType().Assembly.GetName().Version.ToString(),
                ClientRequestId = this._clientRequestId,
                SessionId       = _sessionId,
                IsSuccess       = true,
            };

            if (this.MyInvocation != null && this.MyInvocation.BoundParameters != null)
            {
                QosEvent.Parameters = string.Join(" ",
                                                  this.MyInvocation.BoundParameters.Keys.Select(
                                                      s => string.Format(CultureInfo.InvariantCulture, "-{0} ***", s)));
            }

            if (this.DefaultProfile != null &&
                this.DefaultProfile.Context != null &&
                this.DefaultProfile.Context.Account != null &&
                this.DefaultProfile.Context.Account.Id != null)
            {
                QosEvent.Uid = MetricHelper.GenerateSha256HashString(
                    this.DefaultProfile.Context.Account.Id.ToString());
            }
            else
            {
                QosEvent.Uid = "defaultid";
            }
        }