Skip to content

Commit

Permalink
refactor diagnostic setting
Browse files Browse the repository at this point in the history
  • Loading branch information
VeryEarly committed Nov 19, 2020
1 parent cfca026 commit dbb9250
Show file tree
Hide file tree
Showing 21 changed files with 2,106 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,12 @@ public void TestSetAzureRmDiagnosticSettingLogAnalytics()
{
TestsController.NewInstance.RunPsTest(_logger, "Test-SetAzureRmDiagnosticSetting-LogAnalytics");
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetAzDiagnosticSettingCategory()
{
TestsController.NewInstance.RunPsTest(_logger, "Test-GetAzDiagnosticSettingCategory");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,36 @@ function Test-SetAzureRmDiagnosticSetting-LogAnalytics
}
}

<#
.SYNOPSIS
Test Get diagnostic setting supported categories
#>
function Test-GetAzDiagnosticSettingCategory
{
$ResourceGroupName = 'group' + (getAssetName)
$SubnetConfigName = 'config' + (getAssetName)
$VNetName = 'vn' + (getAssetName)

try
{
$rg = New-AzResourceGroup -Name $ResourceGroupName -Location 'eastus'
$subnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetConfigName -AddressPrefix "10.0.1.0/24"
$vn = New-AzVirtualNetwork -Name $VNetName -ResourceGroupName $ResourceGroupName -Location 'eastus' -AddressPrefix "10.0.0.0/16" -Subnet $subnet

$id = $vn.Id
$log = Get-AzDiagnosticSettingCategory -TargetResourceId $id -Name 'VMProtectionAlerts'
$metric = Get-AzDiagnosticSettingCategory -TargetResourceId $id -Name 'AllMetrics'

Assert-AreEqual 'Logs' $log.CategoryType
Assert-AreEqual 'Metrics' $metric.CategoryType

Remove-AzVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $VNetName -Force
}
finally
{
Remove-AzResourceGroup -Name $ResourceGroupName
}
}


# TODO add more complicated scenarios after we have a definitive subscription

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions src/Monitor/Monitor/Az.Monitor.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,10 @@ FunctionsToExport = @()
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = 'Get-AzMetricDefinition', 'Get-AzMetric', 'Remove-AzLogProfile',
'Get-AzLogProfile', 'Add-AzLogProfile', 'Get-AzActivityLog',
'New-AzDiagnosticSetting',
'New-AzDiagnosticDetailSetting',
'Set-AzDiagnosticSetting', 'Get-AzDiagnosticSetting',
'Get-AzDiagnosticSettingCategory',
'Remove-AzDiagnosticSetting', 'New-AzAutoscaleNotification',
'New-AzAutoscaleProfile', 'New-AzAutoscaleRule',
'Add-AzAutoscaleSetting', 'Get-AzAutoscaleHistory',
Expand Down
4 changes: 4 additions & 0 deletions src/Monitor/Monitor/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
-->

## Upcoming Release
* Added new cmdlets:
`Get-AzDiagnosticSettingCategory`,
`New-AzDiagnosticSetting`,
`New-AzDiagnosticDetailSetting`

## Version 2.2.0
* Fixed the bug that warning message cannot be suppressed. [#12889]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.Insights.OutputClasses;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Azure.Management.Monitor.Models;
using Microsoft.WindowsAzure.Commands.Utilities.Common;

namespace Microsoft.Azure.Commands.Insights.Diagnostics
{
[Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DiagnosticSettingCategory"), OutputType(typeof(PSDiagnosticSettingCategory))]
public class GetAzureRmDiagnosticSettingCategoryCommand : ManagementCmdletBase
{
#region Parameters declarations

[Parameter(Mandatory = true, HelpMessage = "Target resource Id")]
[ValidateNotNullOrEmpty]
public string TargetResourceId { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Name of diagnostic setting category")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }

#endregion

protected override void ProcessRecordInternal()
{
if (this.IsParameterBound(c => c.Name))
{
WriteObject(new PSDiagnosticSettingCategory(this.MonitorManagementClient
.DiagnosticSettingsCategory
.Get(TargetResourceId, Name)));
}
else
{
WriteObject(this.MonitorManagementClient
.DiagnosticSettingsCategory
.List(TargetResourceId)
.Value
.Select(x => new PSDiagnosticSettingCategory(x)).ToList(), true);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Commands.Insights.OutputClasses;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Azure.Management.Monitor.Models;
using Microsoft.WindowsAzure.Commands.Utilities.Common;

namespace Microsoft.Azure.Commands.Insights.Diagnostics
{
[Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DiagnosticDetailSetting"), OutputType(typeof(PSDiagnosticDetailSettings))]
public class NewAzureRmDiagnosticDetailSettingCommand : ManagementCmdletBase
{
public const string LogSettingParameterSet = "LogSettingParameterSet";
public const string MetricSettingParameterSet = "MetricSettingParameterSet";

#region Parameters declarations

[Parameter(ParameterSetName = LogSettingParameterSet, Mandatory = true, HelpMessage = "To create log setting")]
public SwitchParameter Log { get; set; }

[Parameter(ParameterSetName = MetricSettingParameterSet, Mandatory = true, HelpMessage = "To create metric setting")]
public SwitchParameter Metric { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Retention days for retention policy")]
public int RetentionInDays { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Enable Retention policy")]
public SwitchParameter RetentionEnabled { get; set; }

[Parameter(Mandatory = true, HelpMessage = "Category of setting")]
public string Category { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Enable the setting")]
public SwitchParameter Enabled { get; set; }

[Parameter(ParameterSetName = MetricSettingParameterSet, Mandatory = false, HelpMessage = "TimeGrain for metric setting")]
public System.TimeSpan? TimeGrain { get; set; }

#endregion

protected override void ProcessRecordInternal()
{


PSRetentionPolicy policy;
if (!this.IsParameterBound(c => c.RetentionInDays) && !this.IsParameterBound(c => c.RetentionEnabled))
{
policy = null;
}
else
{
policy = new PSRetentionPolicy()
{
Days = this.IsParameterBound(c => c.RetentionInDays) ? this.RetentionInDays : 0,
Enabled = this.IsParameterBound(c => RetentionEnabled) ? true : false
};
}

PSDiagnosticDetailSettings setting;

if (this.ParameterSetName.Equals(LogSettingParameterSet))
{
setting = new PSLogSettings()
{
RetentionPolicy = policy,
Category = this.Category,
Enabled = this.IsParameterBound(c => c.Enabled) ? true : false,
CategoryType = PSDiagnosticSettingCategoryType.Logs
};
}
else
{
setting = new PSMetricSettings()
{
RetentionPolicy = policy,
Category = this.Category,
Enabled = this.IsParameterBound(c => c.Enabled) ? true : false,
TimeGrain = this.TimeGrain,
CategoryType = PSDiagnosticSettingCategoryType.Metrics
};
}

WriteObject(setting);
}
}
}
156 changes: 156 additions & 0 deletions src/Monitor/Monitor/Diagnostics/NewAzureRmDiagnosticSettingCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Commands.Insights.OutputClasses;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Azure.Management.Monitor.Models;
using Microsoft.WindowsAzure.Commands.Utilities.Common;

namespace Microsoft.Azure.Commands.Insights.Diagnostics
{
[Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DiagnosticSetting"), OutputType(typeof(PSServiceDiagnosticSettings))]
public class NewAzureRmDiagnosticSettingCommand : ManagementCmdletBase
{
public const string StorageAccountIdParamName = "StorageAccountId";
public const string ServiceBusRuleIdParamName = "ServiceBusRuleId";
public const string EventHubNameParamName = "EventHubName";
public const string EventHubRuleIdParamName = "EventHubAuthorizationRuleId";
public const string WorkspacetIdParamName = "WorkspaceId";
public const string EnabledParamName = "Enabled";
public const string EnableLogParamName = "EnableLog";
public const string EnableMetricsParamName = "EnableMetrics";

#region Parameters declarations

/// <summary>
/// Gets or sets the resourceId parameter of the cmdlet
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource id")]
[ValidateNotNullOrEmpty]
public string TargetResourceId { get; set; }

/// <summary>
/// Gets or sets the resourceId parameter of the cmdlet
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the diagnostic setting. Defaults to 'service'")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }

/// <summary>
/// Gets or sets the storage account parameter of the cmdlet
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The storage account id")]
public string StorageAccountId { get; set; }

/// <summary>
/// Gets or sets the service bus rule id parameter of the cmdlet
/// </summary>
[Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The service bus rule id")]
public string ServiceBusRuleId { get; set; }

/// <summary>
/// Gets or sets the service bus rule id parameter of the cmdlet
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The service bus rule id")]
public string EventHubName { get; set; }

/// <summary>
/// Gets or sets the event hub authorization rule id parameter of the cmdlet
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The event hub rule id")]
public string EventHubAuthorizationRuleId { get; set; }

/// <summary>
/// Gets or sets the OMS workspace Id
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource Id of the Log Analytics workspace to send logs/metrics to")]
public string WorkspaceId { get; set; }

/// <summary>
/// Gets or sets the retention in days
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The value indicating whether to export (to ODS) to resource-specific (if present) or to AzureDiagnostics (default, not present)")]
public SwitchParameter DedicatedLogAnalyticsDestinationType { get; set; }

/// <summary>
/// Set list of diagnostic settings
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Metric settings or Log settings")]
public PSDiagnosticDetailSettings[] Setting { get; set; }

#endregion

protected override void ProcessRecordInternal()
{
Validate();

IList<MetricSettings> metrics = new List<MetricSettings>();
IList<LogSettings> logs = new List<LogSettings>();

if (this.IsParameterBound(c => c.Setting) && Setting.Length != 0)
{
foreach (PSDiagnosticDetailSettings setting in Setting)
{
switch (setting.CategoryType)
{
case PSDiagnosticSettingCategoryType.Metrics:
metrics.Add(((PSMetricSettings)setting).GetMetricSetting());
break;
case PSDiagnosticSettingCategoryType.Logs:
logs.Add(((PSLogSettings)setting).GetLogSetting());
break;
default:
throw new ArgumentException("Invalid diagnostic setting type");
}
}
}

PSServiceDiagnosticSettings DiagnosticSetting = new PSServiceDiagnosticSettings()
{
StorageAccountId = this.IsParameterBound(c => c.StorageAccountId) ? this.StorageAccountId : null,
ServiceBusRuleId = this.IsParameterBound(c => c.ServiceBusRuleId) ? this.ServiceBusRuleId : null,
EventHubName = this.IsParameterBound(c => c.EventHubName) ? this.EventHubName : null,
EventHubAuthorizationRuleId = this.IsParameterBound(c => c.EventHubAuthorizationRuleId) ? this.EventHubAuthorizationRuleId : null,
WorkspaceId = this.IsParameterBound(c => c.WorkspaceId) ? this.WorkspaceId : null,
LogAnalyticsDestinationType = this.IsParameterBound(c => c.DedicatedLogAnalyticsDestinationType) ? "Dedicated" : null,
Metrics = metrics,
Logs = logs,
Id = this.TargetResourceId + "/diagnosticSettings/" + this.Name,
Name = this.Name
};

WriteObject(DiagnosticSetting);
}

protected void Validate()
{
if (!this.IsParameterBound(c => c.StorageAccountId) &&
!this.IsParameterBound(c => c.ServiceBusRuleId) &&
!this.IsParameterBound(c => c.EventHubName) &&
!this.IsParameterBound(c => c.EventHubAuthorizationRuleId) &&
!this.IsParameterBound(c => c.WorkspaceId))
{
throw new ArgumentException("No operation is specified, please specify storage account Id/service bus rule Id/eventhub name/eventhub authorization rule Id/workspace Id");
}

if (!this.IsParameterBound(c => c.WorkspaceId) && this.IsParameterBound(c => c.DedicatedLogAnalyticsDestinationType))
{
throw new ArgumentException("Please provide workspace Id if want to use dedicated log analytics destination type");
}
}
}
}
Loading

0 comments on commit dbb9250

Please sign in to comment.