public AddAzureRmMetricAlertRuleTests(ITestOutputHelper output) { XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); insightsAlertRuleOperationsMock = new Mock <IAlertOperations>(); insightsManagementClientMock = new Mock <InsightsManagementClient>(); commandRuntimeMock = new Mock <ICommandRuntime>(); cmdlet = new AddAzureRmMetricAlertRuleCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; response = new AzureOperationResponse() { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, }; insightsAlertRuleOperationsMock.Setup(f => f.CreateOrUpdateRuleAsync(It.IsAny <string>(), It.IsAny <RuleCreateOrUpdateParameters>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult <AzureOperationResponse>(response)) .Callback((string resourceGrp, RuleCreateOrUpdateParameters createOrUpdateParams, CancellationToken t) => { resourceGroup = resourceGrp; createOrUpdatePrms = createOrUpdateParams; }); insightsManagementClientMock.SetupGet(f => f.AlertOperations).Returns(this.insightsAlertRuleOperationsMock.Object); }
protected override RuleCreateOrUpdateParameters CreateSdkCallParameters() { RuleCondition condition = this.CreateRuleCondition(); WriteVerboseWithTimestamp(string.Format("CreateSdkCallParameters: Creating rule object")); var rule = new RuleCreateOrUpdateParameters() { Location = this.Location, Properties = new Rule() { Name = this.Name, IsEnabled = !this.DisableRule, Description = this.Description ?? Utilities.GetDefaultDescription("log alert rule"), LastUpdatedTime = DateTime.Now, Condition = condition, Actions = this.Actions, }, // DO NOT REMOVE OR CHANGE the following. The two elements in the Tags are required by other services. Tags = new LazyDictionary <string, string>(), }; if (!string.IsNullOrEmpty(this.TargetResourceId)) { rule.Tags.Add("$type", "Microsoft.WindowsAzure.Management.Common.Storage.CasePreservedDictionary,Microsoft.WindowsAzure.Management.Common.Storage"); rule.Tags.Add("hidden-link:" + this.TargetResourceId, "Resource"); } return(rule); }
private bool TryHandleCreateAsync(object client, IDictionary <string, object> parameters, out Action undoAction) { undoAction = null; RuleCreateOrUpdateParameters ruleCreateOrUpdateParameters = parameters["parameters"] as RuleCreateOrUpdateParameters; PropertyInfo rulesOperationsProperty = this.GetServiceClientType(client).GetProperty("Rules"); MethodInfo undoMethod = rulesOperationsProperty.PropertyType.GetMethod("DeleteAsync"); ParameterInfo[] deleteParameters = undoMethod.GetParameters(); if (deleteParameters.Length < 1 || deleteParameters[0].ParameterType != typeof(string)) { TraceParameterError(this, "CreateOrUpdateAsync", parameters); return(false); } undoAction = () => { object serviceClient = this.CreateServiceClient(client); object rulesOperations = rulesOperationsProperty.GetValue(serviceClient); undoMethod.Invoke(rulesOperations, new object[] { ruleCreateOrUpdateParameters.Rule.Id }); IDisposable disposableClient = serviceClient as IDisposable; if (disposableClient != null) { disposableClient.Dispose(); } }; return(true); }
/// <summary> /// Execute the cmdlet /// </summary> protected override void ProcessRecordInternal() { RuleCreateOrUpdateParameters parameters = this.CreateSdkCallParameters(); var result = this.InsightsManagementClient.AlertOperations.CreateOrUpdateRuleAsync(resourceGroupName: this.ResourceGroup, parameters: parameters).Result; WriteObject(result); }
private void AreEqual(RuleCreateOrUpdateParameters exp, RuleCreateOrUpdateParameters act) { if (exp != null) { Assert.Equal(exp.Location, act.Location); AreEqual(exp.Properties, act.Properties); AreEqual(exp.Tags, act.Tags); } }
/// <summary> /// Execute the cmdlet /// </summary> protected override void ProcessRecordInternal() { WriteWarning("This cmdlet is being modified to enable better experience and may contain breaking changes in a future release."); RuleCreateOrUpdateParameters parameters = this.CreateSdkCallParameters(); var result = this.InsightsManagementClient.AlertOperations.CreateOrUpdateRuleAsync(resourceGroupName: this.ResourceGroup, parameters: parameters).Result; WriteObject(result); }
public void CreateOrUpdateRuleTest() { RuleCreateOrUpdateParameters expectedParameters = GetCreateOrUpdateRuleParameter(); var handler = new RecordedDelegatingHandler(); var insightsClient = GetInsightsManagementClient(handler); insightsClient.AlertOperations.CreateOrUpdateRule(resourceGroupName: "rg1", parameters: expectedParameters); var actualParameters = JsonExtensions.FromJson <RuleCreateOrUpdateParameters>(handler.Request); AreEqual(expectedParameters, actualParameters); }
private static void CreateOrUpdateAlert( InsightsManagementClient insightsClient, string resourceGroupName, string insightsResourceUri, string webTestUri) { string webTestName = GetNameFromUri(webTestUri); string alertName = string.Format("{0}-alert", webTestName); var parameters = new RuleCreateOrUpdateParameters { Location = "East US", Properties = new Rule() { Name = alertName, Description = string.Empty, IsEnabled = true, LastUpdatedTime = DateTime.UtcNow, Action = new RuleEmailAction { SendToServiceOwners = true }, Condition = new LocationThresholdRuleCondition { DataSource = new RuleMetricDataSource { MetricName = "GSMT_AvRaW", ResourceUri = webTestUri }, FailedLocationCount = 1, WindowSize = TimeSpan.FromMinutes(5) }, }, Tags = { { string.Format("hidden-link:{0}", insightsResourceUri), "Resource" }, { string.Format("hidden-link:{0}", webTestUri), "Resource" } } }; var alertCreateOrUpdateResult = insightsClient.AlertOperations.CreateOrUpdateRuleAsync( resourceGroupName, parameters).Result; if (alertCreateOrUpdateResult.StatusCode != HttpStatusCode.Created && alertCreateOrUpdateResult.StatusCode != HttpStatusCode.OK) { throw new InvalidOperationException( string.Format("Unable to create resource '{0}' (HTTP Status Code: {1}).", insightsResourceUri, alertCreateOrUpdateResult.StatusCode)); } }
/// <summary> /// Execute the cmdlet /// </summary> public override void ExecuteCmdlet() { try { RuleCreateOrUpdateParameters parameters = this.CreateSdkCallParameters(); var result = this.InsightsManagementClient.AlertOperations.CreateOrUpdateRuleAsync(resourceGroupName: this.ResourceGroup, parameters: parameters).Result; WriteObject(result); } catch (AggregateException ex) { throw ex.Flatten().InnerException; } }
/// <summary> /// Adds tags for web test alert. /// </summary> /// <param name="parameters"><see cref="RuleCreateOrUpdateParameters"/> instance.</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 tags added.</returns> public static RuleCreateOrUpdateParameters AddTags(this RuleCreateOrUpdateParameters parameters, ResourceBaseExtended webTest, ResourceBaseExtended insights) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (webTest == null) { throw new ArgumentNullException(nameof(webTest)); } if (insights == null) { throw new ArgumentNullException(nameof(insights)); } parameters.Tags.Add($"hidden-link:{insights.Id}", "Resource"); parameters.Tags.Add($"hidden-link:{webTest.Id}", "Resource"); return(parameters); }
private static void CreateAlertRule(string authorizationToken) { string token = GetAuthorizationHeader(); TokenCloudCredentials credentials = new TokenCloudCredentials(subscriptionId, token); InsightsManagementClient client = new InsightsManagementClient(credentials, new Uri(ServiceUrl)); RuleCreateOrUpdateParameters parameters = new RuleCreateOrUpdateParameters(); List <RuleAction> actions = new List <RuleAction>(); //The new RuleWebhookAction has two properties - the uri and a property bag, which can be key value pairs //Lets create some key-value pairs to be added as properties for this webhook Dictionary <string, string> properties = new Dictionary <string, string>(); properties.Add("Hello1", "World1!"); properties.Add("json_stuff", "{\"type\":\"critical\", \"color\":\"red\"}'"); properties.Add("customId", "wd39ue9832ue9iuhd9iuewhd9edh"); properties.Add("send_emails_to", "*****@*****.**"); // NOTE: you can add up to 5 webhooks for an alert programmatically // if you configure multiple webhooks programmtically, you can only view/edit the 1st one via the Azure Portal UI // We will add the ability to configure multiple webhooks via the portal soon // my runscope uri actions.Add(new RuleWebhookAction() { ServiceUri = "your_runscope_uri", Properties = properties }); //pager_duty uri actions.Add(new RuleWebhookAction() { ServiceUri = "your_pagerduty_uri", Properties = properties }); parameters.Properties = new Rule() { Name = "Alert_webhook_demo1", Action = new RuleEmailAction() { CustomEmails = new List <string>() { "*****@*****.**" } }, IsEnabled = true, Actions = actions, Condition = new ThresholdRuleCondition() { DataSource = new RuleMetricDataSource() { MetricName = "\\Memory\\Available Bytes", ResourceUri = "your_resource_id" }, Operator = ConditionOperator.GreaterThan, Threshold = 1.0, TimeAggregation = TimeAggregationOperator.Average, WindowSize = TimeSpan.FromMinutes(5), } }; parameters.Location = "location_for_your_alert_rule"; // e.g "eastus" var response = client.AlertOperations.CreateOrUpdateRule("your_resoureGroupeName", parameters); Console.WriteLine("Alert created with a webhook!"); }
/// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Monitoring.Alerts.IRuleOperations. /// </param> /// <param name='parameters'> /// Required. The rule to create or update. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task <OperationResponse> CreateOrUpdateAsync(this IRuleOperations operations, RuleCreateOrUpdateParameters parameters) { return(operations.CreateOrUpdateAsync(parameters, CancellationToken.None)); }
/// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Monitoring.Alerts.IRuleOperations. /// </param> /// <param name='parameters'> /// Required. The rule to create or update. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse CreateOrUpdate(this IRuleOperations operations, RuleCreateOrUpdateParameters parameters) { return(Task.Factory.StartNew((object s) => { return ((IRuleOperations)s).CreateOrUpdateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }
/// <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(); } } }
/// <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); }
/// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Monitoring.Alerts.IRuleOperations. /// </param> /// <param name='parameters'> /// The rule to create or update. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse CreateOrUpdate(this IRuleOperations operations, RuleCreateOrUpdateParameters parameters) { try { return(operations.CreateOrUpdateAsync(parameters).Result); } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } }
/// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAlertOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. The rule to create or update. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task <OperationResponse> CreateOrUpdateRuleAsync(this IAlertOperations operations, string resourceGroupName, RuleCreateOrUpdateParameters parameters) { return(operations.CreateOrUpdateRuleAsync(resourceGroupName, parameters, CancellationToken.None)); }
/// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAlertOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. The rule to update. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse UpdateRule(this IAlertOperations operations, string resourceGroupName, RuleCreateOrUpdateParameters parameters) { return(Task.Factory.StartNew((object s) => { return ((IAlertOperations)s).UpdateRuleAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }