public GetAzureRmAlertRuleTests(ITestOutputHelper output) { XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output)); insightsAlertRuleOperationsMock = new Mock <IAlertOperations>(); insightsManagementClientMock = new Mock <InsightsManagementClient>(); commandRuntimeMock = new Mock <ICommandRuntime>(); cmdlet = new GetAzureRmAlertRuleCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; listResponse = Utilities.InitializeRuleListResponse(); singleResponse = Utilities.InitializeRuleGetResponse(); insightsAlertRuleOperationsMock.Setup(f => f.ListRulesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult <RuleListResponse>(listResponse)) .Callback((string resourceGrp, string nameOrTargetUri, CancellationToken t) => { resourceGroup = resourceGrp; ruleNameOrTargetUri = nameOrTargetUri; }); insightsAlertRuleOperationsMock.Setup(f => f.GetRuleAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult <RuleGetResponse>(singleResponse)) .Callback((string resourceGrp, string nameOrTargetUri, CancellationToken t) => { resourceGroup = resourceGrp; ruleNameOrTargetUri = nameOrTargetUri; }); insightsManagementClientMock.SetupGet(f => f.AlertOperations).Returns(this.insightsAlertRuleOperationsMock.Object); }
/// <summary> /// Initializes a new instance of the PSAlertRule class. /// </summary> /// <param name="ruleSpec"></param> public PSAlertRuleNoDetails(RuleGetResponse ruleSpec) { this.Id = ruleSpec.Id; this.Location = ruleSpec.Location; this.Name = ruleSpec.Name; this.Properties = ruleSpec.Properties; this.Tags = ruleSpec.Tags; }
/// <summary> /// Initializes a new instance of the PSAlertRule class. /// </summary> /// <param name="ruleSpec"></param> public PSAlertRule(RuleGetResponse ruleSpec) { this.Id = ruleSpec.Id; this.Location = ruleSpec.Location; this.Name = ruleSpec.Name; this.Properties = new PSAlertRuleProperty(ruleSpec.Properties); this.Tags = new PSDictionaryElement(ruleSpec.Tags); }
/// <summary> /// Execute the cmdlet /// </summary> protected override void ExecuteCmdletInternal() { if (string.IsNullOrWhiteSpace(this.Name)) { // Retrieve all the AlertRules for a ResourceGroup RuleListResponse result = this.InsightsManagementClient.AlertOperations.ListRulesAsync(resourceGroupName: this.ResourceGroup, targetResourceUri: this.TargetResourceId).Result; var records = result.RuleResourceCollection.Value.Select(e => this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor) new PSAlertRule(e) : new PSAlertRuleNoDetails(e)); WriteObject(sendToPipeline: records.ToList()); } else { // Retrieve a single AlertRule determined by the ResourceGroup and the rule name RuleGetResponse result = this.InsightsManagementClient.AlertOperations.GetRuleAsync(resourceGroupName: this.ResourceGroup, ruleName: this.Name).Result; var finalResult = new List <PSManagementItemDescriptor> { this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor) new PSAlertRule(result) : new PSAlertRuleNoDetails(result) }; WriteObject(sendToPipeline: finalResult); } }
/// <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."); if (string.IsNullOrWhiteSpace(this.Name)) { // Retrieve all the AlertRules for a ResourceGroup RuleListResponse result = this.InsightsManagementClient.AlertOperations.ListRulesAsync(resourceGroupName: this.ResourceGroup, targetResourceUri: this.TargetResourceId).Result; var records = result.RuleResourceCollection.Value.Select(e => this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor) new PSAlertRule(e) : new PSAlertRuleNoDetails(e)); WriteObject(sendToPipeline: records.ToList()); } else { // Retrieve a single AlertRule determined by the ResourceGroup and the rule name RuleGetResponse result = this.InsightsManagementClient.AlertOperations.GetRuleAsync(resourceGroupName: this.ResourceGroup, ruleName: this.Name).Result; var finalResult = new List <PSManagementItemDescriptor> { this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor) new PSAlertRule(result) : new PSAlertRuleNoDetails(result) }; WriteObject(sendToPipeline: finalResult); } }
/// <summary> /// Execute the cmdlet /// </summary> public override void ExecuteCmdlet() { try { if (string.IsNullOrWhiteSpace(this.Name)) { // Retrieve all the AlertRules for a ResourceGroup RuleListResponse result = this.InsightsManagementClient.AlertOperations.ListRulesAsync(resourceGroupName: this.ResourceGroup, targetResourceUri: this.TargetResourceUri).Result; var records = result.RuleResourceCollection.Value.Select(e => this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor) new PSAlertRule(e) : new PSAlertRuleNoDetails(e)); WriteObject(sendToPipeline: records, enumerateCollection: true); } else { // Retrieve a single AlertRule determined by the ResourceGroup and the rule name RuleGetResponse result = this.InsightsManagementClient.AlertOperations.GetRuleAsync(resourceGroupName: this.ResourceGroup, ruleName: this.Name).Result; WriteObject(sendToPipeline: this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor) new PSAlertRule(result) : new PSAlertRuleNoDetails(result)); } } catch (AggregateException ex) { throw ex.Flatten().InnerException; } }
/// <param name='ruleId'> /// The id of the rule to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Rule operation response. /// </returns> public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleGetResponse> GetAsync(string ruleId, CancellationToken cancellationToken) { // Validate if (ruleId == null) { throw new ArgumentNullException("ruleId"); } // 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("ruleId", ruleId); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = new Uri(this.Client.BaseUri, "/").AbsoluteUri + this.Client.Credentials.SubscriptionId + "/services/monitoring/alertrules/" + ruleId; // 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 RuleGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RuleGetResponse(); JToken responseDoc = JToken.Parse(responseContent); if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Rule ruleInstance = new Rule(); result.Rule = ruleInstance; JToken idValue = responseDoc["Id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = (string)idValue; ruleInstance.Id = idInstance; } JToken nameValue = responseDoc["Name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = (string)nameValue; ruleInstance.Name = nameInstance; } JToken descriptionValue = responseDoc["Description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = (string)descriptionValue; ruleInstance.Description = descriptionInstance; } JToken isEnabledValue = responseDoc["IsEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = (bool)isEnabledValue; ruleInstance.IsEnabled = isEnabledInstance; } JToken conditionValue = responseDoc["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 = responseDoc["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 = responseDoc["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(); } } }
public void AlertRuleCrudTest() { var handler = new RecordedDelegatingHandler() { }; using (UndoContext context = UndoContext.Current) { context.Start(); var alertsClient = GetAlertsClient(handler); // provision a hosted service to consume by the test case string newServiceName = TestUtilities.GenerateName("cs"); var deploymentStatus = ProvisionHostedService(newServiceName); var deployment = deploymentStatus.Deployments.FirstOrDefault(); var id = HttpMockServer.GetVariable("RuleID", Guid.NewGuid().ToString()); Assert.NotNull(deployment); // now the actual test case Rule newRule = new Rule { Name = TestUtilities.GenerateName("rule"), Description = "rule description", Id = id, IsEnabled = false, Condition = new ThresholdRuleCondition { Operator = ConditionOperator.GreaterThanOrEqual, Threshold = 80.0, WindowSize = TimeSpan.FromMinutes(5), DataSource = new RuleMetricDataSource { MetricName = "Percentage CPU", ResourceId = string.Format("/hostedservices/{0}/deployments/{1}/roles/{2}", newServiceName, deployment.Name, deployment.Roles.FirstOrDefault().RoleName), MetricNamespace = MetricNamespace.None } } }; newRule.Actions.Add(new RuleEmailAction()); // Create the rule AzureOperationResponse createRuleResponse = alertsClient.Rules.CreateOrUpdate(new RuleCreateOrUpdateParameters { Rule = newRule }); Assert.Equal(HttpStatusCode.Created, createRuleResponse.StatusCode); Console.WriteLine("Created alert rule {0}", newRule.Name); // Retrieve the rule RuleGetResponse getRuleResponse = alertsClient.Rules.Get(newRule.Id); Assert.Equal(HttpStatusCode.OK, getRuleResponse.StatusCode); Assert.True(AreEquivalent(newRule, getRuleResponse.Rule), "The retrieved rule is not equivalent to the original rule"); // Get incidents for the rule IncidentListResponse incidentListResponse = alertsClient.Incidents.ListForRule(newRule.Id, true); Assert.Equal(HttpStatusCode.OK, incidentListResponse.StatusCode); Assert.False(incidentListResponse.Any(), string.Format("There should be no active incident for the rule [{0}].", newRule.Name)); // Validate rule is included by list operation RuleListResponse listRulesResponse = alertsClient.Rules.List(); Assert.Equal(HttpStatusCode.OK, getRuleResponse.StatusCode); Assert.True(listRulesResponse.Value.Any(), "The alertClient.Rules.List() call returned an empty collection of alert rules"); Assert.True(listRulesResponse.Value.Any(rc => rc.Id.Equals(newRule.Id)), "The newly created rule is not in present in the collection of rules returned by alertClient.Rules.List()"); // Update and validate the rule Rule updatedRule = newRule; updatedRule.Description = "updated description"; ((ThresholdRuleCondition)(updatedRule.Condition)).Threshold = 60.0; AzureOperationResponse updateRuleResponse = alertsClient.Rules.CreateOrUpdate(new RuleCreateOrUpdateParameters { Rule = updatedRule }); Assert.Equal(HttpStatusCode.OK, updateRuleResponse.StatusCode); getRuleResponse = alertsClient.Rules.Get(newRule.Id); Assert.Equal(HttpStatusCode.OK, getRuleResponse.StatusCode); Assert.True(AreEquivalent(updatedRule, getRuleResponse.Rule), "The retrieved rule is not equivalent to the updated rule"); // Delete the rule AzureOperationResponse deleteResponse = alertsClient.Rules.Delete(newRule.Id); Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode); // Validate the rule was deleted Assert.Throws <CloudException>(() => alertsClient.Rules.Get(newRule.Id)); listRulesResponse = alertsClient.Rules.List(); Assert.Equal(HttpStatusCode.OK, getRuleResponse.StatusCode); if (listRulesResponse.Value.Count > 0) { var foundDeletedRule = listRulesResponse.Value.Any(rc => rc.Id.Equals(newRule.Id)); Assert.False(foundDeletedRule, string.Format("Rule [{0}] is found after its deletion.", newRule.Name)); } } }