Esempio n. 1
0
        public async Task <Response <AlertRuleResource> > CreateOrUpdateAsync(string resourceGroupName, string ruleName, AlertRuleResource parameters, CancellationToken cancellationToken = default)
        {
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (ruleName == null)
            {
                throw new ArgumentNullException(nameof(ruleName));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using var message = CreateCreateOrUpdateRequest(resourceGroupName, ruleName, parameters);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            case 201:
            {
                AlertRuleResource value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value = AlertRuleResource.DeserializeAlertRuleResource(document.RootElement);
                return(Response.FromValue(value, message.Response));
            }
        protected override AlertRuleResource CreateSdkCallParameters()
        {
            WriteWarning("*** This cmdlet will be removed in the 5.0 release (November 2017.)");
            WriteWarning("*** Note: After October 1st using this cmdlet will no longer have any effect as this functionality is being transitioned to Activity Log Alerts. Please see https://aka.ms/migratemealerts for more information.");

            RuleCondition condition = this.CreateRuleCondition();

            WriteVerboseWithTimestamp(string.Format("CreateSdkCallParameters: Creating rule object"));
            var rule = new AlertRuleResource()
            {
                Description           = this.Description ?? Utilities.GetDefaultDescription("log alert rule"),
                Condition             = condition,
                Actions               = this.Actions,
                Location              = this.Location,
                IsEnabled             = !this.DisableRule,
                AlertRuleResourceName = this.Name,

                // DO NOT REMOVE OR CHANGE the following. The two elements in the Tags are required by other services.
                Tags = new Dictionary <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);
        }
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            WriteWarning("The output of this cmdlet will be flattened, i.e. elimination of the properties field, in a future release to improve the user experience.");
            if (string.IsNullOrWhiteSpace(this.Name))
            {
                // Retrieve all the AlertRules for a ResourceGroup
                IEnumerable <AlertRuleResource> result = this.MonitorManagementClient.AlertRules.ListByResourceGroupAsync(resourceGroupName: this.ResourceGroup).Result;

                // The filter on targetResourceId is not supported by the servers, not specified in in Swagger, nor supported by the SDK.
                // This is added to maintain support in PowerShell
                if (!string.IsNullOrWhiteSpace(this.TargetResourceId))
                {
                    result = result.Where(a => string.Equals(this.TargetResourceId, ExtractTargetResourceId(a), StringComparison.OrdinalIgnoreCase));
                }

                var records = result.Select(e => this.DetailedOutput.IsPresent ? (PSManagementItemDescriptor) new PSAlertRule(e) : new PSAlertRuleNoDetails(e));
                WriteObject(sendToPipeline: records.ToList(), enumerateCollection: true);
            }
            else
            {
                // Retrieve a single AlertRule determined by the ResourceGroup and the rule name
                AlertRuleResource result = this.MonitorManagementClient.AlertRules.GetAsync(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, enumerateCollection: true);
            }
        }
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            this.WriteIdentifiedWarning(
                cmdletName: this.GetCmdletName(),
                topic: "Parameter name change",
                message: "The parameter plural names for the parameters will be deprecated in a future breaking change release in favor of the singular versions of the same names.");
            if (ShouldProcess(
                    target: string.Format("Create/update an alert rule: {0} from resource group: {1}", this.Name, this.ResourceGroupName),
                    action: "Create/update an alert rule"))
            {
                AlertRuleResource parameters = this.CreateSdkCallParameters();

                // Part of the result of this operation is operation (result.Body ==> a AutoscaleSettingResource) is being discarded for backwards compatibility
                var result = this.MonitorManagementClient.AlertRules.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName: this.ResourceGroupName, parameters: parameters, ruleName: parameters.AlertRuleResourceName).Result;

                var response = new PSAddAlertRuleOperationResponse
                {
                    RequestId  = result.RequestId,
                    StatusCode = result.Response != null ? result.Response.StatusCode : HttpStatusCode.OK,
                    AlertRule  = result.Body
                };

                WriteObject(response);
            }
        }
        public AddAzureRmMetricAlertRuleTests(ITestOutputHelper output)
        {
            //XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
            insightsAlertRuleOperationsMock = new Mock <IAlertRulesOperations>();
            insightsManagementClientMock    = new Mock <InsightsManagementClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new AddAzureRmMetricAlertRuleCommand()
            {
                CommandRuntime           = commandRuntimeMock.Object,
                InsightsManagementClient = insightsManagementClientMock.Object
            };

            AlertRuleResource alertRuleResourceInput = new AlertRuleResource(alertRuleResourceName: "a name", location: null, isEnabled: true);

            response = new Rest.Azure.AzureOperationResponse <AlertRuleResource>()
            {
                Body = alertRuleResourceInput
            };

            insightsAlertRuleOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <AlertRuleResource>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Rest.Azure.AzureOperationResponse <AlertRuleResource> >(response))
            .Callback((string resourceGrp, string name, AlertRuleResource alertRuleResourceIn, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceGroup     = resourceGrp;
                alertRuleResource = alertRuleResourceIn;
            });

            insightsManagementClientMock.SetupGet(f => f.AlertRules).Returns(this.insightsAlertRuleOperationsMock.Object);
        }
Esempio n. 6
0
        public AddAzureRmWebtestAlertRuleTests(ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsAlertRuleOperationsMock = new Mock <IAlertRulesOperations>();
            insightsManagementClientMock    = new Mock <MonitorManagementClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new AddAzureRmWebtestAlertRuleCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            AlertRuleResource alertRuleResourceInput = new AlertRuleResource()
            {
                Location              = null,
                IsEnabled             = true,
                AlertRuleResourceName = "a name"
            };

            response = new Rest.Azure.AzureOperationResponse <AlertRuleResource>()
            {
                Body = alertRuleResourceInput
            };

            insightsAlertRuleOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <AlertRuleResource>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Rest.Azure.AzureOperationResponse <AlertRuleResource> >(response))
            .Callback((string resourceGrp, string name, AlertRuleResource createOrUpdateParams, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceGroup      = resourceGrp;
                createOrUpdatePrms = createOrUpdateParams;
            });

            insightsManagementClientMock.SetupGet(f => f.AlertRules).Returns(this.insightsAlertRuleOperationsMock.Object);
        }
        /// <summary>
        /// Initializes a new instance of the PSRuleProperties class.
        /// </summary>
        /// <param name="properties"></param>
        public PSAlertRuleProperty(AlertRuleResource properties)
        {
            this.Actions = properties.Actions;

            var condition = properties.Condition as ThresholdRuleCondition;

            if (condition != null)
            {
                this.Condition = new PSThresholdRuleCondition(condition);
            }
            else
            {
                var eventCondition = properties.Condition as ManagementEventRuleCondition;
                if (eventCondition != null)
                {
                    this.Condition = new PSEventRuleCondition(eventCondition);
                }
                else
                {
                    var locationCondition = properties.Condition as LocationThresholdRuleCondition;
                    if (locationCondition != null)
                    {
                        this.Condition = new PSLocationThresholdRuleCondition(locationCondition);
                    }
                    else
                    {
                        throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourcesForAlertCmdlets.RuleConditionTypeNotSupported, properties.Condition.GetType().Name));
                    }
                }
            }

            this.Description = properties.Description;
            this.Status      = properties.IsEnabled ? "Enabled" : "Disabled";
            this.Name        = properties.Name;
        }
Esempio n. 8
0
        protected override AlertRuleResource CreateSdkCallParameters()
        {
            RuleCondition condition = this.CreateRuleCondition();

            WriteVerboseWithTimestamp(string.Format("CreateSdkCallParameters: Creating rule object"));
            var rule = new AlertRuleResource(
                location: this.Location,
                isEnabled: !this.DisableRule,
                alertRuleResourceName: this.Name)
            {
                Description = this.Description ?? Utilities.GetDefaultDescription("log alert rule"),
                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 Dictionary <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);
        }
        public AddAzureRmWebtestAlertRuleTests(ITestOutputHelper output)
        {
            //XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
            insightsAlertRuleOperationsMock = new Mock<IAlertRulesOperations>();
            insightsManagementClientMock = new Mock<InsightsManagementClient>();
            commandRuntimeMock = new Mock<ICommandRuntime>();
            cmdlet = new AddAzureRmWebtestAlertRuleCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsManagementClient = insightsManagementClientMock.Object
            };

            AlertRuleResource alertRuleResourceInput = new AlertRuleResource(location: null, isEnabled: true, alertRuleResourceName: "a name");
            response = new Rest.Azure.AzureOperationResponse<AlertRuleResource>()
            {
                Body = alertRuleResourceInput
            };

            insightsAlertRuleOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<AlertRuleResource>(), It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult<Rest.Azure.AzureOperationResponse<AlertRuleResource>>(response))
                .Callback((string resourceGrp, string name, AlertRuleResource createOrUpdateParams, Dictionary<string, List<string>> headers, CancellationToken t) =>
                {
                    resourceGroup = resourceGrp;
                    createOrUpdatePrms = createOrUpdateParams;
                });

            insightsManagementClientMock.SetupGet(f => f.AlertRules).Returns(this.insightsAlertRuleOperationsMock.Object);
        }
        /// <summary>
        /// Initializes a new instance of the PSRuleProperties class.
        /// </summary>
        /// <param name="properties"></param>
        public PSAlertRuleProperty(AlertRuleResource properties)
        {
            this.Actions = properties.Actions;

            var condition = properties.Condition as ThresholdRuleCondition;
            if (condition != null)
            {
                this.Condition = new PSThresholdRuleCondition(condition);
            }
            else
            {
                var eventCondition = properties.Condition as ManagementEventRuleCondition;
                if (eventCondition != null)
                {
                    this.Condition = new PSEventRuleCondition(eventCondition);
                }
                else
                {
                    var locationCondition = properties.Condition as LocationThresholdRuleCondition;
                    if (locationCondition != null)
                    {
                        this.Condition = new PSLocationThresholdRuleCondition(locationCondition);
                    }
                    else
                    {
                        throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourcesForAlertCmdlets.RuleConditionTypeNotSupported, properties.Condition.GetType().Name));
                    }
                }
            }

            this.Description = properties.Description;
            this.Status = properties.IsEnabled ? "Enabled" : "Disabled";
            this.Name = properties.Name;
        }
Esempio n. 11
0
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            this.WriteIdentifiedWarning(
                cmdletName: "Get-AzAlertRule",
                topic: "Parameter deprecation",
                message: "The DetailedOutput parameter will be deprecated in a future breaking change release.");
            if (string.IsNullOrWhiteSpace(this.Name))
            {
                // Retrieve all the AlertRules for a ResourceGroup
                IEnumerable <AlertRuleResource> result = this.MonitorManagementClient.AlertRules.ListByResourceGroupAsync(resourceGroupName: this.ResourceGroupName).Result;

                // The filter on targetResourceId is not supported by the servers, not specified in in Swagger, nor supported by the SDK.
                // This is added to maintain support in PowerShell
                if (!string.IsNullOrWhiteSpace(this.TargetResourceId))
                {
                    result = result.Where(a => string.Equals(this.TargetResourceId, ExtractTargetResourceId(a), StringComparison.OrdinalIgnoreCase));
                }

                var records = result.Select(e => this.DetailedOutput.IsPresent ? new PSAlertRule(e) : new PSAlertRuleNoDetails(e));
                WriteObject(sendToPipeline: records.ToList(), enumerateCollection: true);
            }
            else
            {
                // Retrieve a single AlertRule determined by the ResourceGroup and the rule name
                AlertRuleResource result = this.MonitorManagementClient.AlertRules.GetAsync(resourceGroupName: this.ResourceGroupName, ruleName: this.Name).Result;

                var finalResult = new List <PSAlertRule> {
                    this.DetailedOutput.IsPresent ? new PSAlertRule(result) : new PSAlertRuleNoDetails(result)
                };
                WriteObject(sendToPipeline: finalResult, enumerateCollection: true);
            }
        }
Esempio n. 12
0
 /// <summary>
 /// Initializes a new instance of the PSAlertRule class.
 /// </summary>
 /// <param name="ruleSpec"></param>
 public PSAlertRule(AlertRuleResource ruleSpec)
 {
     this.Id = ruleSpec.Id;
     this.Location = ruleSpec.Location;
     this.Name = ruleSpec.Name;
     this.Properties = new PSAlertRuleProperty(ruleSpec);
     this.Tags = new PSDictionaryElement(ruleSpec.Tags);
 }
Esempio n. 13
0
 /// <summary>
 /// Initializes a new instance of the PSAlertRule class.
 /// </summary>
 /// <param name="ruleSpec"></param>
 public PSAlertRule(AlertRuleResource ruleSpec)
 {
     this.Id         = ruleSpec.Id;
     this.Location   = ruleSpec.Location;
     this.Name       = ruleSpec.Name;
     this.Properties = new PSAlertRuleProperty(ruleSpec);
     this.Tags       = new PSDictionaryElement(ruleSpec.Tags);
 }
Esempio n. 14
0
        public static IEnumerable <AlertRuleResource> InitializeRuleListResponse()
        {
            AlertRuleResource ruleResource = Utilities.CreateFakeRuleResource();

            return(new List <AlertRuleResource>()
            {
                ruleResource
            });
        }
Esempio n. 15
0
        public async Task Get()
        {
            var alertName = Recording.GenerateAssetName("testAlertRule-");
            var alert     = await CreateAlertRuleAsync(alertName);

            AlertRuleResource actionGroup2 = await alert.GetAsync();

            ResourceDataHelper.AssertAlertRule(alert.Data, actionGroup2.Data);
        }
        /// <summary>
        /// Initializes a new instance of the PSAlertRule class.
        /// </summary>
        /// <param name="ruleSpec"></param>
        public PSAlertRuleNoDetails(AlertRuleResource ruleSpec)
        {
            this.Id = ruleSpec.Id;
            this.Location = ruleSpec.Location;
            this.Name = ruleSpec.Name;

            this.Properties = ruleSpec;
            this.Tags = ruleSpec.Tags;
        }
Esempio n. 17
0
        /// <summary>
        /// Initializes a new instance of the PSAlertRule class.
        /// </summary>
        /// <param name="ruleSpec"></param>
        public PSAlertRuleNoDetails(AlertRuleResource ruleSpec)
        {
            this.Id       = ruleSpec.Id;
            this.Location = ruleSpec.Location;
            this.Name     = ruleSpec.Name;

            this.Properties = ruleSpec;
            this.Tags       = ruleSpec.Tags;
        }
Esempio n. 18
0
        public async Task Get()
        {
            var collection = await GetAlertRuleCollectionAsync();

            var actionGroupName = Recording.GenerateAssetName("testAlertRule", DefaultSubscription.Id);
            var input           = ResourceDataHelper.GetBasicAlertRuleData(DefaultLocation);
            var lro             = await collection.CreateOrUpdateAsync(WaitUntil.Completed, actionGroupName, input);

            AlertRuleResource alert1 = lro.Value;
            AlertRuleResource alert2 = await collection.GetAsync(actionGroupName);

            ResourceDataHelper.AssertAlertRule(alert1.Data, alert2.Data);
        }
Esempio n. 19
0
 private void AreEqual(AlertRuleResource exp, AlertRuleResource act)
 {
     if (exp != null)
     {
         Assert.AreEqual(exp.Location, act.Location);
         AreEqual(exp.Tags, act.Tags);
         Assert.AreEqual(exp.Name, act.Name);
         Assert.AreEqual(exp.Description, act.Description);
         Assert.AreEqual(exp.IsEnabled, act.IsEnabled);
         AreEqual(exp.Condition, act.Condition);
         AreEqual(exp.Actions, act.Actions);
     }
 }
Esempio n. 20
0
 /// <summary>
 /// Initializes a new instance of the PSAlertRule class.
 /// </summary>
 /// <param name="ruleSpec"></param>
 public PSAlertRule(AlertRuleResource ruleSpec)
     : base(
         location: ruleSpec.Location,
         alertRuleResourceName: ruleSpec.AlertRuleResourceName,
         isEnabled: ruleSpec.IsEnabled,
         condition: ruleSpec.Condition,
         id: ruleSpec.Id,
         name: ruleSpec.Name,
         type: ruleSpec.Type,
         tags: ruleSpec.Tags,
         description: ruleSpec.Description,
         actions: ruleSpec.Actions,
         lastUpdatedTime: ruleSpec.LastUpdatedTime)
 {
 }
Esempio n. 21
0
 /// <summary>
 /// Initializes a new instance of the PSAlertRuleResource class.
 /// </summary>
 /// <param name="ruleSpec"></param>
 public PSAlertRuleResource(AlertRuleResource ruleSpec)
     : base(
         id: ruleSpec.Id,
         location: ruleSpec.Location,
         name: ruleSpec.Name,
         type: ruleSpec.Type,
         alertRuleResourceName: ruleSpec.Name,
         isEnabled: ruleSpec.IsEnabled,
         condition: ruleSpec.Condition,
         lastUpdatedTime: ruleSpec.LastUpdatedTime)
 {
     this.Tags        = ruleSpec.Tags;
     this.Actions     = ruleSpec.Actions;
     this.Description = ruleSpec.Description;
 }
Esempio n. 22
0
 private static void Check(AlertRuleResource act)
 {
     if (act != null)
     {
         Assert.False(string.IsNullOrWhiteSpace(act.Name));
         Assert.Equal(act.Name, act.AlertRuleResourceName);
         Assert.False(string.IsNullOrWhiteSpace(act.Id));
         Assert.False(string.IsNullOrWhiteSpace(act.Location));
         Assert.False(string.IsNullOrWhiteSpace(act.Type));
     }
     else
     {
         // Guarantee failure, act should not be null
         Assert.NotNull(act);
     }
 }
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            AlertRuleResource parameters = this.CreateSdkCallParameters();

            // Part of the result of this operation is operation (result.Body ==> a AutoscaleSettingResource) is being discarded for backwards compatibility
            var result = this.MonitorManagementClient.AlertRules.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName: this.ResourceGroup, parameters: parameters, ruleName: parameters.AlertRuleResourceName).Result;

            var response = new PSAddAlertRuleOperationResponse
            {
                RequestId  = result.RequestId,
                StatusCode = result.Response != null ? result.Response.StatusCode : HttpStatusCode.OK,
                AlertRule  = result.Body
            };

            WriteObject(response);
        }
 public static void AreEqual(AlertRuleResource exp, AlertRuleResource act)
 {
     if (exp != null)
     {
         Assert.Equal(exp.Location, act.Location);
         AreEqual(exp.Tags, act.Tags);
         Assert.Equal(exp.Name, act.Name);
         Assert.Equal(exp.Description, act.Description);
         Assert.Equal(exp.IsEnabled, act.IsEnabled);
         AreEqual(exp.Condition, act.Condition);
         AreEqual(exp.Actions, act.Actions);
         //Assert.Equal(exp.LastUpdatedTime, act.LastUpdatedTime);
     }
     else
     {
         Assert.Null(act);
     }
 }
Esempio n. 25
0
        public void CreateOrUpdateRuleTest()
        {
            AlertRuleResource expectedParameters = GetCreateOrUpdateRuleParameter();

            var handler          = new RecordedDelegatingHandler();
            var insightsClient   = GetInsightsManagementClient(handler);
            var serializedObject = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(expectedParameters, insightsClient.SerializationSettings);
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(serializedObject)
            };

            handler        = new RecordedDelegatingHandler(expectedResponse);
            insightsClient = GetInsightsManagementClient(handler);

            var result = insightsClient.AlertRules.CreateOrUpdate(resourceGroupName: "rg1", ruleName: expectedParameters.Name, parameters: expectedParameters);

            AreEqual(expectedParameters, result);
        }
Esempio n. 26
0
        public async Task AlertRulesGetTest()
        {
            AlertRuleResource expectedParameters = GetCreateOrUpdateRuleParameter();
            var mockResponse = new MockResponse((int)HttpStatusCode.OK);
            var content      = @"{
                    'namePropertiesName': 'name1',
                    'id': null,
                    'name': 'name1',
                    'type': null,
                    'location': 'location',
                    'tags': {
                                'key1': 'val1'
                    },
                    'properties': {
                        'description': 'description',
                        'isEnabled': true,
                        'condition': {
                                        'dataSource': {
                                                        'resourceUri': 'resourceUri'
                                                      }
                                     },
                        'actions': [
                            {
                                'odata.type':'Microsoft.Azure.Management.Insights.Models.RuleEmailAction',
                                'sendToServiceOwners': true,
                                'customEmails': [
                                    'emailid1'
                                ]
                    }
                        ],
                        'lastUpdatedTime': '2020-09-22T07:43:19.9383848+00:00'
                    }
                }
            ".Replace("'", "\"");

            mockResponse.SetContent(content);
            var mockTransport  = new MockTransport(mockResponse);
            var insightsClient = GetInsightsManagementClient(mockTransport);
            var result         = (await insightsClient.AlertRules.GetAsync("rg1", "rule1")).Value;

            AreEqual(expectedParameters, result);
        }
Esempio n. 27
0
        private AlertRuleResource CreateAlertRuleFor500Errors(string resUri, IResourceGroup resGrpName)
        {
            _logger.Info("CreateAlertRuleFor500Errors - Create");
            var alertRuleConfig = (IAlertRuleConfiguration)_appconfig;
            var actions         = ConfigureRuleAction(alertRuleConfig);
            var conditions      = ConfigureRuleThresholds(resUri);

            var alertRuleResource = new AlertRuleResource(
                name: alertRuleConfig.RuleName,
                description: "500 Errors Thrown",
                location: "eastus2",
                alertRuleResourceName: resGrpName.Name,
                actions: actions,
                condition: conditions,
                isEnabled: true,
                lastUpdatedTime: DateTime.Now
                );

            return(alertRuleResource);
        }
Esempio n. 28
0
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            WriteWarning("This output of this cmdlet will change in the next release to return the updated or newly created object.");
            AlertRuleResource parameters = this.CreateSdkCallParameters();

            // Part of the result of this operation is operation (result.Body ==> a AutoscaleSettingResource) is being discarded for backwards compatibility
            var result = this.InsightsManagementClient.AlertRules.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName: this.ResourceGroup, parameters: parameters, ruleName: parameters.AlertRuleResourceName).Result;

            // Keep this response for backwards compatibility.
            // Note: Create operations return the newly created object in the new specification, i.e. need to use result.Body
            var response = new List <AzureOperationResponse>
            {
                new AzureOperationResponse()
                {
                    RequestId  = result.RequestId,
                    StatusCode = HttpStatusCode.OK
                }
            };

            WriteObject(response);
        }
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            if (ShouldProcess(
                    target: string.Format("Create/update an alert rule: {0} from resource group: {1}", this.Name, this.ResourceGroupName),
                    action: "Create/update an alert rule"))
            {
                AlertRuleResource parameters = this.CreateSdkCallParameters();

                // Part of the result of this operation is operation (result.Body ==> a AutoscaleSettingResource) is being discarded for backwards compatibility
                var result = this.MonitorManagementClient.AlertRules.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName: this.ResourceGroupName, parameters: parameters, ruleName: parameters.AlertRuleResourceName).Result;

                var response = new PSAddAlertRuleOperationResponse
                {
                    RequestId  = result.RequestId,
                    StatusCode = result.Response != null ? result.Response.StatusCode : HttpStatusCode.OK,
                    AlertRule  = new Management.Monitor.Management.Models.AlertRuleResource(result.Body)
                };

                WriteObject(response);
            }
        }
Esempio n. 30
0
        private static string ExtractTargetResourceId(AlertRuleResource alertRuleResource)
        {
            var cond = alertRuleResource.Condition as LocationThresholdRuleCondition;

            if (cond != null)
            {
                return(ExtractTargetResourceId(cond.DataSource));
            }

            var cond1 = alertRuleResource.Condition as ManagementEventRuleCondition;

            if (cond1 != null)
            {
                return(ExtractTargetResourceId(cond1.DataSource));
            }

            var cond2 = alertRuleResource.Condition as ThresholdRuleCondition;

            // The types above are the only supported types. The string.Empty is a prevention only
            return(cond2 != null?ExtractTargetResourceId(cond2.DataSource) : string.Empty);
        }
Esempio n. 31
0
        public void UpdateRulesTest()
        {
            AlertRuleResource resource = GetRuleResourceCollection().FirstOrDefault();

            resource.IsEnabled = false;
            resource.Tags      = new Dictionary <string, string>()
            {
                { "key2", "val2" }
            };

            var handler = new RecordedDelegatingHandler();
            var monitorManagementClient = GetMonitorManagementClient(handler);
            var serializedObject        = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resource, monitorManagementClient.SerializationSettings);

            serializedObject = serializedObject.Replace("{", "{\"name\":\"" + resource.Name + "\",\"id\":\"" + resource.Id + "\",");
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(serializedObject)
            };

            handler = new RecordedDelegatingHandler(expectedResponse);
            monitorManagementClient = GetMonitorManagementClient(handler);

            AlertRuleResourcePatch pathResource = new AlertRuleResourcePatch(
                name: resource.Name,
                isEnabled: false,
                tags: new Dictionary <string, string>()
            {
                { "key2", "val2" }
            },
                actions: resource.Actions,
                condition: resource.Condition,
                description: resource.Description,
                lastUpdatedTime: resource.LastUpdatedTime
                );

            var actualResponse = monitorManagementClient.AlertRules.Update(resourceGroupName: "rg1", ruleName: resource.Name, alertRulesResource: pathResource);

            Utilities.AreEqual(resource, actualResponse);
        }
Esempio n. 32
0
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            if (string.IsNullOrWhiteSpace(this.Name))
            {
                // Retrieve all the AlertRules for a ResourceGroup
                ODataQuery <AlertRuleResource>  query  = new ODataQuery <AlertRuleResource>(this.TargetResourceId);
                IEnumerable <AlertRuleResource> result = this.InsightsManagementClient.AlertRules.ListByResourceGroupAsync(resourceGroupName: this.ResourceGroup, odataQuery: query).Result;

                var records = result.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
                AlertRuleResource result = this.InsightsManagementClient.AlertRules.GetAsync(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);
            }
        }
Esempio n. 33
0
        public void MetricBasedRule()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                MonitorManagementClient insightsClient = GetMonitorManagementClient(context, handler);
                this.VerifyExistenceOrCreateResourceGroup(resourceGroupName: ResourceGroupName, location: Location);

                AlertRuleResource expectedParameters = GetCreateOrUpdateRuleParameter(insightsClient.SubscriptionId);
                AlertRuleResource result             = insightsClient.AlertRules.CreateOrUpdate(
                    resourceGroupName: ResourceGroupName,
                    ruleName: RuleName,
                    parameters: expectedParameters);

                if (!this.IsRecording)
                {
                    Check(result);
                }

                AlertRuleResource retrievedRule = insightsClient.AlertRules.Get(
                    resourceGroupName: ResourceGroupName,
                    ruleName: RuleName);

                if (!this.IsRecording)
                {
                    Check(retrievedRule);

                    Utilities.AreEqual(result, retrievedRule);
                }

                IEnumerable <AlertRuleResource> enumOfRules = insightsClient.AlertRules.ListByResourceGroup(
                    resourceGroupName: ResourceGroupName);

                if (!this.IsRecording)
                {
                    var listOfRules = enumOfRules.ToList();
                    var selected    = listOfRules.Where(r => string.Equals(r.Id, retrievedRule.Id, StringComparison.OrdinalIgnoreCase)).ToList();

                    Assert.NotNull(selected);
                    Assert.NotEmpty(selected);
                    Assert.True(selected.Count == 1);
                    Utilities.AreEqual(retrievedRule, selected[0]);
                }

                var newTags = new Dictionary <string, string>()
                {
                    { "key2", "val2" }
                };

                // TODO: Update is requiring 'location', but it was not specified so.
                AlertRuleResourcePatch pathResource = new AlertRuleResourcePatch(
                    name: retrievedRule.Name,
                    isEnabled: !retrievedRule.IsEnabled,
                    tags: newTags,
                    actions: retrievedRule.Actions,
                    condition: retrievedRule.Condition,
                    description: retrievedRule.Description,
                    lastUpdatedTime: retrievedRule.LastUpdatedTime
                    );

                AlertRuleResource updatedRule = null;
                Assert.Throws <ErrorResponseException>(
                    () => updatedRule = insightsClient.AlertRules.Update(
                        resourceGroupName: ResourceGroupName,
                        ruleName: RuleName,
                        alertRulesResource: pathResource));

                if (!this.IsRecording && updatedRule != null)
                {
                    Check(updatedRule);

                    Assert.NotEqual(retrievedRule.Tags, updatedRule.Tags);
                    Assert.True(retrievedRule.IsEnabled = !updatedRule.IsEnabled);
                    Assert.Equal(retrievedRule.Name, updatedRule.Name);
                    Assert.Equal(retrievedRule.Location, updatedRule.Location);
                    Assert.Equal(retrievedRule.Id, updatedRule.Id);
                }

                AlertRuleResource retrievedUpdatedRule = insightsClient.AlertRules.Get(
                    resourceGroupName: ResourceGroupName,
                    ruleName: RuleName);

                if (!this.IsRecording && updatedRule != null)
                {
                    Check(retrievedRule);

                    Utilities.AreEqual(updatedRule, retrievedUpdatedRule);
                }

                insightsClient.AlertRules.Delete(
                    resourceGroupName: ResourceGroupName,
                    ruleName: RuleName);

                Assert.Throws <ErrorResponseException>(
                    () => insightsClient.AlertRules.Get(
                        resourceGroupName: ResourceGroupName,
                        ruleName: RuleName));
            }
        }
        protected override AlertRuleResource CreateSdkCallParameters()
        {
            RuleCondition condition = this.CreateRuleCondition();

            WriteVerboseWithTimestamp(string.Format("CreateSdkCallParameters: Creating rule object"));
            var rule = new AlertRuleResource(
                location: this.Location,
                isEnabled: !this.DisableRule,
                alertRuleResourceName: this.Name)
            {
                Description = this.Description ?? Utilities.GetDefaultDescription("log alert rule"),
                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 Dictionary<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;
        }
 /// <summary>
 /// Initializes a new instance of the PSAlertRule class.
 /// </summary>
 /// <param name="ruleSpec">The original AlertRuleResource</param>
 public PSAlertRuleNoDetails(AlertRuleResource ruleSpec)
     :
     base(ruleSpec)
 {
 }