/// <summary>
        /// A string representation of the RuleMetricDataSource including indentation
        /// </summary>
        /// <param name="ruleMetricDataSource">The RuleMetricDataSource object</param>
        /// <param name="indentationTabs">The number of tabs to insert in front of each member</param>
        /// <returns>A string representation of the RuleMetricDataSource including indentation</returns>
        public static string ToString(this RuleMetricDataSource ruleMetricDataSource, int indentationTabs)
        {
            StringBuilder output = new StringBuilder();

            if (ruleMetricDataSource != null)
            {
                output.AppendLine();
                output.AddSpacesInFront(indentationTabs).AppendLine("MetricName  : " + ruleMetricDataSource.MetricName);
                output.AddSpacesInFront(indentationTabs).Append("ResourceUri : " + ruleMetricDataSource.ResourceUri);
            }

            return(output.ToString());
        }
        private LocationThresholdRuleCondition CreateRuleCondition()
        {
            WriteVerboseWithTimestamp(string.Format("CreateRuleCondition: Creating location threshold rule condition (webtest rule)"));
            var dataSource = new RuleMetricDataSource
            {
                MetricName  = this.MetricName,
                ResourceUri = this.TargetResourceUri
            };

            return(new LocationThresholdRuleCondition
            {
                DataSource = dataSource,
                FailedLocationCount = this.FailedLocationCount,
                WindowSize = this.WindowSize
            });
        }
        public static AlertRuleData GetBasicAlertRuleData(AzureLocation location)
        {
            var ruleWebhookAction = new RuleWebhookAction()
            {
                ServiceUri = new Uri("https://www.contoso.com/alerts?type=HighCPU"),
                Properties = { new KeyValuePair <string, string>("key1", "value1") }
            };
            //RuleMetricDataSource ruleDataSource = new RuleMetricDataSource(
            //    "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
            //    "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/Default-EventHub-1375/providers/Microsoft.EventHub/namespaces/sdk-eventhub-Namespace-8280",
            //    "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/Default-EventHub-1375/providers/microsoft.insights/metricalerts/testAlertRule",
            //    "global",
            //    "Microsoft.EventHub/namespaces",
            //    "ActiveConnections");
            RuleMetricDataSource ruleDataSource = new RuleMetricDataSource()
            {
                //LegacyResourceId = "",
                MetricName       = "testrulemetric",
                MetricNamespace  = "Microsoft.Compute/virtualMachines",
                ResourceLocation = location,
                ResourceId       = "/subscriptions/db1ab6f0-4769-4b27-930e-01e2ef9c123c/resourceGroups/deleteme0122/providers/Microsoft.Compute/virtualMachines/MetricAlertActionTestVM01"
            };
            //var ruleCondition = new ThresholdRuleCondition(
            //    "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria",
            //    ruleDataSource,
            //    ConditionOperator.GreaterThan,
            //    3.0,
            //    TimeSpan.FromMinutes(15),
            //    TimeAggregationOperator.Average);
            var ruleCondition = new ThresholdRuleCondition(ConditionOperator.GreaterThan, 3.0)
            {
                WindowSize      = TimeSpan.FromMinutes(15),
                TimeAggregation = TimeAggregationOperator.Average,
                DataSource      = ruleDataSource
            };
            var data = new AlertRuleData(location, "testAlertRule", true, ruleCondition)
            {
                Actions = { ruleWebhookAction }
            };

            return(data);
        }
Exemple #4
0
        /// <param name='parameters'>
        /// The rule to create or update.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationResponse> CreateOrUpdateAsync(RuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").AbsoluteUri + this.Client.Credentials.SubscriptionId + "/services/monitoring/alertrules/" + parameters.Rule.Id;

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-10-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                if (parameters.Rule != null)
                {
                    JObject ruleValue = new JObject();
                    requestDoc = ruleValue;

                    if (parameters.Rule.Id != null)
                    {
                        ruleValue["Id"] = parameters.Rule.Id;
                    }

                    if (parameters.Rule.Name != null)
                    {
                        ruleValue["Name"] = parameters.Rule.Name;
                    }

                    if (parameters.Rule.Description != null)
                    {
                        ruleValue["Description"] = parameters.Rule.Description;
                    }

                    ruleValue["IsEnabled"] = parameters.Rule.IsEnabled;

                    if (parameters.Rule.Condition != null)
                    {
                        JObject conditionValue = new JObject();
                        ruleValue["Condition"]       = conditionValue;
                        conditionValue["odata.type"] = parameters.Rule.Condition.GetType().FullName;
                        if (parameters.Rule.Condition is ThresholdRuleCondition)
                        {
                            ThresholdRuleCondition derived = (ThresholdRuleCondition)parameters.Rule.Condition;

                            if (derived.DataSource != null)
                            {
                                JObject dataSourceValue = new JObject();
                                conditionValue["DataSource"]  = dataSourceValue;
                                dataSourceValue["odata.type"] = derived.DataSource.GetType().FullName;
                                if (derived.DataSource is RuleMetricDataSource)
                                {
                                    RuleMetricDataSource derived2 = (RuleMetricDataSource)derived.DataSource;

                                    if (derived2.ResourceId != null)
                                    {
                                        dataSourceValue["ResourceId"] = derived2.ResourceId;
                                    }

                                    if (derived2.MetricNamespace != null)
                                    {
                                        dataSourceValue["MetricNamespace"] = derived2.MetricNamespace;
                                    }

                                    if (derived2.MetricName != null)
                                    {
                                        dataSourceValue["MetricName"] = derived2.MetricName;
                                    }
                                }
                            }

                            conditionValue["Operator"] = derived.Operator.ToString();

                            conditionValue["Threshold"] = derived.Threshold;

                            conditionValue["WindowSize"] = TypeConversion.To8601String(derived.WindowSize);
                        }
                    }

                    if (parameters.Rule.Actions != null)
                    {
                        JArray actionsArray = new JArray();
                        foreach (RuleAction actionsItem in parameters.Rule.Actions)
                        {
                            JObject ruleActionValue = new JObject();
                            actionsArray.Add(ruleActionValue);
                            ruleActionValue["odata.type"] = actionsItem.GetType().FullName;
                            if (actionsItem is RuleEmailAction)
                            {
                                RuleEmailAction derived3 = (RuleEmailAction)actionsItem;

                                ruleActionValue["SendToServiceOwners"] = derived3.SendToServiceOwners;

                                if (derived3.CustomEmails != null)
                                {
                                    JArray customEmailsArray = new JArray();
                                    foreach (string customEmailsItem in derived3.CustomEmails)
                                    {
                                        customEmailsArray.Add(customEmailsItem);
                                    }
                                    ruleActionValue["CustomEmails"] = customEmailsArray;
                                }
                            }
                        }
                        ruleValue["Actions"] = actionsArray;
                    }

                    ruleValue["LastUpdatedTime"] = parameters.Rule.LastUpdatedTime;
                }

                requestContent      = requestDoc.ToString(Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    OperationResponse result = null;
                    result            = new OperationResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// List the alert rules within a subscription.
        /// </summary>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Rules operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleListResponse> ListAsync(CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").AbsoluteUri + this.Client.Credentials.SubscriptionId + "/services/monitoring/alertrules";

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-10-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    RuleListResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new RuleListResponse();
                    JToken responseDoc = JToken.Parse(responseContent);

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        JToken valueArray = responseDoc["Value"];
                        if (valueArray != null && valueArray.Type != JTokenType.Null)
                        {
                            foreach (JToken valueValue in (JArray)valueArray)
                            {
                                Rule ruleInstance = new Rule();
                                result.Value.Add(ruleInstance);

                                JToken idValue = valueValue["Id"];
                                if (idValue != null && idValue.Type != JTokenType.Null)
                                {
                                    string idInstance = (string)idValue;
                                    ruleInstance.Id = idInstance;
                                }

                                JToken nameValue = valueValue["Name"];
                                if (nameValue != null && nameValue.Type != JTokenType.Null)
                                {
                                    string nameInstance = (string)nameValue;
                                    ruleInstance.Name = nameInstance;
                                }

                                JToken descriptionValue = valueValue["Description"];
                                if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
                                {
                                    string descriptionInstance = (string)descriptionValue;
                                    ruleInstance.Description = descriptionInstance;
                                }

                                JToken isEnabledValue = valueValue["IsEnabled"];
                                if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null)
                                {
                                    bool isEnabledInstance = (bool)isEnabledValue;
                                    ruleInstance.IsEnabled = isEnabledInstance;
                                }

                                JToken conditionValue = valueValue["Condition"];
                                if (conditionValue != null && conditionValue.Type != JTokenType.Null)
                                {
                                    string typeName = (string)conditionValue["odata.type"];
                                    if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition")
                                    {
                                        ThresholdRuleCondition thresholdRuleConditionInstance = new ThresholdRuleCondition();

                                        JToken dataSourceValue = conditionValue["DataSource"];
                                        if (dataSourceValue != null && dataSourceValue.Type != JTokenType.Null)
                                        {
                                            string typeName2 = (string)dataSourceValue["odata.type"];
                                            if (typeName2 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource")
                                            {
                                                RuleMetricDataSource ruleMetricDataSourceInstance = new RuleMetricDataSource();

                                                JToken resourceIdValue = dataSourceValue["ResourceId"];
                                                if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                                                {
                                                    string resourceIdInstance = (string)resourceIdValue;
                                                    ruleMetricDataSourceInstance.ResourceId = resourceIdInstance;
                                                }

                                                JToken metricNamespaceValue = dataSourceValue["MetricNamespace"];
                                                if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null)
                                                {
                                                    string metricNamespaceInstance = (string)metricNamespaceValue;
                                                    ruleMetricDataSourceInstance.MetricNamespace = metricNamespaceInstance;
                                                }

                                                JToken metricNameValue = dataSourceValue["MetricName"];
                                                if (metricNameValue != null && metricNameValue.Type != JTokenType.Null)
                                                {
                                                    string metricNameInstance = (string)metricNameValue;
                                                    ruleMetricDataSourceInstance.MetricName = metricNameInstance;
                                                }
                                                thresholdRuleConditionInstance.DataSource = ruleMetricDataSourceInstance;
                                            }
                                        }

                                        JToken operatorValue = conditionValue["Operator"];
                                        if (operatorValue != null && operatorValue.Type != JTokenType.Null)
                                        {
                                            ConditionOperator operatorInstance = (ConditionOperator)Enum.Parse(typeof(ConditionOperator), (string)operatorValue, false);
                                            thresholdRuleConditionInstance.Operator = operatorInstance;
                                        }

                                        JToken thresholdValue = conditionValue["Threshold"];
                                        if (thresholdValue != null && thresholdValue.Type != JTokenType.Null)
                                        {
                                            double thresholdInstance = (double)thresholdValue;
                                            thresholdRuleConditionInstance.Threshold = thresholdInstance;
                                        }

                                        JToken windowSizeValue = conditionValue["WindowSize"];
                                        if (windowSizeValue != null && windowSizeValue.Type != JTokenType.Null)
                                        {
                                            TimeSpan windowSizeInstance = TypeConversion.From8601TimeSpan((string)windowSizeValue);
                                            thresholdRuleConditionInstance.WindowSize = windowSizeInstance;
                                        }
                                        ruleInstance.Condition = thresholdRuleConditionInstance;
                                    }
                                }

                                JToken actionsArray = valueValue["Actions"];
                                if (actionsArray != null && actionsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken actionsValue in (JArray)actionsArray)
                                    {
                                        string typeName3 = (string)actionsValue["odata.type"];
                                        if (typeName3 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction")
                                        {
                                            RuleEmailAction ruleEmailActionInstance = new RuleEmailAction();

                                            JToken sendToServiceOwnersValue = actionsValue["SendToServiceOwners"];
                                            if (sendToServiceOwnersValue != null && sendToServiceOwnersValue.Type != JTokenType.Null)
                                            {
                                                bool sendToServiceOwnersInstance = (bool)sendToServiceOwnersValue;
                                                ruleEmailActionInstance.SendToServiceOwners = sendToServiceOwnersInstance;
                                            }

                                            JToken customEmailsArray = actionsValue["CustomEmails"];
                                            if (customEmailsArray != null && customEmailsArray.Type != JTokenType.Null)
                                            {
                                                foreach (JToken customEmailsValue in (JArray)customEmailsArray)
                                                {
                                                    ruleEmailActionInstance.CustomEmails.Add((string)customEmailsValue);
                                                }
                                            }
                                            ruleInstance.Actions.Add(ruleEmailActionInstance);
                                        }
                                    }
                                }

                                JToken lastUpdatedTimeValue = valueValue["LastUpdatedTime"];
                                if (lastUpdatedTimeValue != null && lastUpdatedTimeValue.Type != JTokenType.Null)
                                {
                                    DateTime lastUpdatedTimeInstance = (DateTime)lastUpdatedTimeValue;
                                    ruleInstance.LastUpdatedTime = lastUpdatedTimeInstance;
                                }
                            }
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Adds properties for web test alert.
        /// </summary>
        /// <param name="parameters"><see cref="RuleCreateOrUpdateParameters"/> instance.</param>
        /// <param name="name">Name of web test.</param>
        /// <param name="element"><see cref="WebTestElement"/> instance from App.config/Web.config.</param>
        /// <param name="webTest"><see cref="ResourceBaseExtended"/> instance representing web test resource.</param>
        /// <param name="insights"><see cref="ResourceBaseExtended"/> instance representing Application Insights resource.</param>
        /// <returns>Returns the <see cref="RuleCreateOrUpdateParameters"/> instance with properties added.</returns>
        public static RuleCreateOrUpdateParameters AddProperties(this RuleCreateOrUpdateParameters parameters, string name, WebTestElement element, ResourceBaseExtended webTest, ResourceBaseExtended insights)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            if (webTest == null)
            {
                throw new ArgumentNullException(nameof(webTest));
            }

            if (insights == null)
            {
                throw new ArgumentNullException(nameof(insights));
            }

            var alertName = $"{name}-{insights.Name}-alert".ToLowerInvariant();

            var action = new RuleEmailAction()
            {
                SendToServiceOwners = element.Alerts.SendAlertToAdmin
            };

            if (!element.Alerts.Recipients.IsNullOrEmpty())
            {
                action.CustomEmails = element.Alerts.Recipients;
            }

            var source = new RuleMetricDataSource()
            {
                MetricName = AlertMetricName, ResourceUri = webTest.Id
            };
            var condition = new LocationThresholdRuleCondition()
            {
                DataSource          = source,
                FailedLocationCount = element.Alerts.AlertLocationThreshold,
                WindowSize          = TimeSpan.FromMinutes((int)element.Alerts.TestAlertFailureTimeWindow),
            };
            var rule = new Rule()
            {
                Name            = alertName,
                Description     = string.Empty,
                IsEnabled       = element.Alerts.IsEnabled,
                LastUpdatedTime = DateTime.UtcNow,
                Actions         = { action },
                Condition       = condition,
            };

            parameters.Properties = rule;

            return(parameters);
        }