From 3e1c47f458c158a0816d1a40b1f4c48718cc33c9 Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Tue, 17 May 2022 10:32:45 +0800 Subject: [PATCH 01/11] track2 initial setup and StorageAccount related cmdlets --- ...PSAzureFilesIdentityBasedAuthentication.cs | 12 +- .../Models/PSBlobRestore.cs | 31 +- .../Models/PSGeoReplicationStats.cs | 20 +- .../Models/PSNetworkRule.cs | 98 +++--- .../Models/PSRoutingPreference.cs | 6 +- .../Models/PSStorageAccount.cs | 294 ++++++++++++------ .../Storage.Management.csproj | 12 + .../StorageAccount/GetAzureStorageAccount.cs | 39 +-- .../StorageAccount/NewAzureStorageAccount.cs | 293 +++++++++-------- .../RemoveAzureStorageAccount.cs | 6 +- .../StorageAccount/SetAzureStorageAccount.cs | 241 +++++++------- .../StorageAccountBaseCmdlet.cs | 115 +++++-- .../Track2StorageManagementClient.cs | 151 +++++++++ 13 files changed, 848 insertions(+), 470 deletions(-) create mode 100644 src/Storage/Storage.Management/Track2StorageManagementClient.cs diff --git a/src/Storage/Storage.Management/Models/PSAzureFilesIdentityBasedAuthentication.cs b/src/Storage/Storage.Management/Models/PSAzureFilesIdentityBasedAuthentication.cs index 14ae48c41f6a..3ce99750875b 100644 --- a/src/Storage/Storage.Management/Models/PSAzureFilesIdentityBasedAuthentication.cs +++ b/src/Storage/Storage.Management/Models/PSAzureFilesIdentityBasedAuthentication.cs @@ -12,19 +12,19 @@ // limitations under the License. // ---------------------------------------------------------------------------------- -using Microsoft.Azure.Management.Storage.Models; +using Track2Models = Azure.ResourceManager.Storage.Models; namespace Microsoft.Azure.Commands.Management.Storage.Models { public class PSAzureFilesIdentityBasedAuthentication { - public PSAzureFilesIdentityBasedAuthentication(AzureFilesIdentityBasedAuthentication auth) + public PSAzureFilesIdentityBasedAuthentication(Track2Models.AzureFilesIdentityBasedAuthentication auth) { if (auth != null) { - this.DirectoryServiceOptions = auth.DirectoryServiceOptions; + this.DirectoryServiceOptions = auth.DirectoryServiceOptions.ToString(); this.ActiveDirectoryProperties = auth.ActiveDirectoryProperties != null ? new PSActiveDirectoryProperties(auth.ActiveDirectoryProperties) : null; - this.DefaultSharePermission = auth.DefaultSharePermission; + this.DefaultSharePermission = auth.DefaultSharePermission.ToString(); } } // Gets or sets indicates the directory service used. Possible values include: 'None','AADDS', 'AD' @@ -35,7 +35,7 @@ public PSAzureFilesIdentityBasedAuthentication(AzureFilesIdentityBasedAuthentica public class PSActiveDirectoryProperties { - public PSActiveDirectoryProperties(ActiveDirectoryProperties properties) + public PSActiveDirectoryProperties(Track2Models.ActiveDirectoryProperties properties) { if (properties != null) { @@ -46,7 +46,7 @@ public PSActiveDirectoryProperties(ActiveDirectoryProperties properties) this.DomainSid = properties.DomainSid; this.AzureStorageSid = properties.AzureStorageSid; this.SamAccountName = properties.SamAccountName; - this.AccountType = properties.AccountType; + this.AccountType = properties.AccountType != null ? properties.AccountType.ToString() : null; } } public string DomainName { get; set; } diff --git a/src/Storage/Storage.Management/Models/PSBlobRestore.cs b/src/Storage/Storage.Management/Models/PSBlobRestore.cs index 8b02e2424584..33384b2d60a6 100644 --- a/src/Storage/Storage.Management/Models/PSBlobRestore.cs +++ b/src/Storage/Storage.Management/Models/PSBlobRestore.cs @@ -17,6 +17,7 @@ using Microsoft.WindowsAzure.Commands.Common.Attributes; using System; using System.Collections.Generic; +using Track2Models = Azure.ResourceManager.Storage.Models; namespace Microsoft.Azure.Commands.Management.Storage.Models { @@ -37,40 +38,32 @@ public PSBlobRestoreRange(string startRange, string endRange) this.EndRange = endRange; } - public PSBlobRestoreRange(BlobRestoreRange range) + public PSBlobRestoreRange(Track2Models.BlobRestoreRange range) { this.StartRange = range.StartRange; this.EndRange = range.EndRange; } - public static IList ParseBlobRestoreRanges(PSBlobRestoreRange[] ranges) + public static IList ParseBlobRestoreRanges(PSBlobRestoreRange[] ranges) { - IList re = new List(); + IList re = new List(); if (ranges == null) { re.Add( - new BlobRestoreRange - { - StartRange = "", - EndRange = "" - }); + new Track2Models.BlobRestoreRange("", "")); } else { foreach (PSBlobRestoreRange range in ranges) { re.Add( - new BlobRestoreRange - { - StartRange = range.StartRange, - EndRange = range.EndRange - }); + new Track2Models.BlobRestoreRange(range.EndRange, range.StartRange)); } } return re; } - public static PSBlobRestoreRange[] ParsePSBlobRestoreRanges(IList ranges) + public static PSBlobRestoreRange[] ParsePSBlobRestoreRanges(IList ranges) { if (ranges == null) { @@ -78,7 +71,7 @@ public static PSBlobRestoreRange[] ParsePSBlobRestoreRanges(IList re = new List(); - foreach (BlobRestoreRange range in ranges) + foreach (Track2Models.BlobRestoreRange range in ranges) { re.Add( new PSBlobRestoreRange @@ -109,11 +102,11 @@ public class PSBlobRestoreStatus public PSBlobRestoreStatus() { } - public PSBlobRestoreStatus(BlobRestoreStatus status) + public PSBlobRestoreStatus(Track2Models.BlobRestoreStatus status) { if (status != null) { - this.Status = status.Status; + this.Status = status.Status != null ? status.Status.ToString() : null; this.FailureReason = status.FailureReason; this.RestoreId = status.RestoreId; this.Parameters = status.Parameters is null ? null : new PSBlobRestoreParameters(status.Parameters); @@ -126,13 +119,13 @@ public PSBlobRestoreStatus(BlobRestoreStatus status) /// public class PSBlobRestoreParameters { - public DateTime TimeToRestore { get; set; } + public DateTimeOffset TimeToRestore { get; set; } public PSBlobRestoreRange[] BlobRanges { get; set; } public PSBlobRestoreParameters() { } - public PSBlobRestoreParameters(BlobRestoreParameters parameters) + public PSBlobRestoreParameters(Track2Models.BlobRestoreContent parameters) { this.TimeToRestore = parameters.TimeToRestore; this.BlobRanges = PSBlobRestoreRange.ParsePSBlobRestoreRanges(parameters.BlobRanges); diff --git a/src/Storage/Storage.Management/Models/PSGeoReplicationStats.cs b/src/Storage/Storage.Management/Models/PSGeoReplicationStats.cs index e7f9eca61d1a..84e1ce90080f 100644 --- a/src/Storage/Storage.Management/Models/PSGeoReplicationStats.cs +++ b/src/Storage/Storage.Management/Models/PSGeoReplicationStats.cs @@ -12,32 +12,32 @@ // limitations under the License. // ---------------------------------------------------------------------------------- -using Microsoft.Azure.Management.Storage.Models; +using Track2Models = Azure.ResourceManager.Storage.Models; using System; namespace Microsoft.Azure.Commands.Management.Storage.Models { public class PSGeoReplicationStats { - //Parse GeoReplicationStats in SDK to wrapped property PSGeoReplicationStats - public static PSGeoReplicationStats ParsePSGeoReplicationStats(GeoReplicationStats geoReplicationStats) + //Parse GeoReplicationStats in SDK to wrapped property PSGeoReplicationStats + public static PSGeoReplicationStats ParsePSGeoReplicationStats(Track2Models.GeoReplicationStats geoReplicationStats) { if (geoReplicationStats == null) { return null; } - PSGeoReplicationStats pSGeoReplicationStats = new PSGeoReplicationStats(); - - pSGeoReplicationStats.Status = geoReplicationStats.Status; - pSGeoReplicationStats.LastSyncTime = geoReplicationStats.LastSyncTime; - pSGeoReplicationStats.CanFailover = geoReplicationStats.CanFailover; - + PSGeoReplicationStats pSGeoReplicationStats = new PSGeoReplicationStats + { + Status = geoReplicationStats.Status != null ? geoReplicationStats.Status.ToString() : null, + LastSyncTime = geoReplicationStats.LastSyncOn, + CanFailover = geoReplicationStats.CanFailover != null ? geoReplicationStats.CanFailover : null + }; return pSGeoReplicationStats; } public string Status { get; set; } - public DateTime? LastSyncTime { get; set; } + public DateTimeOffset? LastSyncTime { get; set; } public bool? CanFailover { get; set; } } } diff --git a/src/Storage/Storage.Management/Models/PSNetworkRule.cs b/src/Storage/Storage.Management/Models/PSNetworkRule.cs index 7bd7e96ef6ef..0bc50bcbfcc8 100644 --- a/src/Storage/Storage.Management/Models/PSNetworkRule.cs +++ b/src/Storage/Storage.Management/Models/PSNetworkRule.cs @@ -16,6 +16,7 @@ using System; using System.Collections.Generic; using Microsoft.WindowsAzure.Commands.Common.Attributes; +using Track2Models = Azure.ResourceManager.Storage.Models; namespace Microsoft.Azure.Commands.Management.Storage.Models { @@ -82,14 +83,14 @@ public class PSNetworkRuleSet //Parse NetworkRule property Action in SDK to wrapped property PSNetworkRuleActionEnum - public static PSNetworkRuleActionEnum? ParsePSNetworkRuleAction(Microsoft.Azure.Management.Storage.Models.Action? action) + public static PSNetworkRuleActionEnum? ParsePSNetworkRuleAction(string action) { if (action == null) { return null; } - if (action.Value == Microsoft.Azure.Management.Storage.Models.Action.Allow) + if (string.Equals(action.ToUpper(), "ALLOW")) { return PSNetworkRuleActionEnum.Allow; } @@ -99,7 +100,7 @@ public class PSNetworkRuleSet //Parse wrapped property PSNetworkRuleActionEnum to NetworkRule rule property Action in SDK - public static Microsoft.Azure.Management.Storage.Models.Action? ParseStorageNetworkRuleAction(PSNetworkRuleActionEnum? action) + public static string ParseStorageNetworkRuleAction(PSNetworkRuleActionEnum? action) { if (action == null) { @@ -108,9 +109,9 @@ public class PSNetworkRuleSet if (action == PSNetworkRuleActionEnum.Allow) { - return Microsoft.Azure.Management.Storage.Models.Action.Allow; + return "Allow"; } - return Microsoft.Azure.Management.Storage.Models.Action.Allow; + return "Allow"; } //Parse NetworkRule property Bypass in SDK to wrapped property PSNetworkRuleBypassEnum @@ -171,9 +172,9 @@ public static string ParseStorageNetworkRuleBypass(PSNetWorkRuleBypassEnum? bypa } //Parse NetworkRule property DefaultAction in SDK to wrapped property PSNetworkRuleDefaultActionEnum - public static PSNetWorkRuleDefaultActionEnum ParsePSNetworkRuleDefaultAction(DefaultAction defaultAction) + public static PSNetWorkRuleDefaultActionEnum ParsePSNetworkRuleDefaultAction(Track2Models.DefaultAction defaultAction) { - if (defaultAction == Microsoft.Azure.Management.Storage.Models.DefaultAction.Allow) + if (defaultAction == Track2Models.DefaultAction.Allow) { return PSNetWorkRuleDefaultActionEnum.Allow; } @@ -184,56 +185,62 @@ public static PSNetWorkRuleDefaultActionEnum ParsePSNetworkRuleDefaultAction(Def } //Parse wrapped property PSNetworkRuleDefaultActionEnum to NetworkRule property DefaultAction in SDK - public static DefaultAction ParseStorageNetworkRuleDefaultAction(PSNetWorkRuleDefaultActionEnum defaultAction) + public static Track2Models.DefaultAction ParseStorageNetworkRuleDefaultAction(PSNetWorkRuleDefaultActionEnum defaultAction) { if (defaultAction == PSNetWorkRuleDefaultActionEnum.Allow) { - return Microsoft.Azure.Management.Storage.Models.DefaultAction.Allow; + return Track2Models.DefaultAction.Allow; } else { - return Microsoft.Azure.Management.Storage.Models.DefaultAction.Deny; + return Track2Models.DefaultAction.Deny; } } //Parse single NetworkRule IpRule in SDK to wrapped property PSIpRule - public static PSIpRule ParsePSNetworkRuleIPRule(IPRule ipRule) + public static PSIpRule ParsePSNetworkRuleIPRule(Track2Models.IPRule ipRule) { - PSIpRule returnRule = new PSIpRule(); - returnRule.Action = ParsePSNetworkRuleAction(ipRule.Action); - returnRule.IPAddressOrRange = ipRule.IPAddressOrRange; + PSIpRule returnRule = new PSIpRule + { + Action = ipRule.Action != null ? ParsePSNetworkRuleAction(ipRule.Action) : null, + IPAddressOrRange = ipRule.IPAddressOrRange + }; return returnRule; } //Parse wrapped property PSIpRule to single NetworkRule IpRule in SDK - public static IPRule ParseStorageNetworkRuleIPRule(PSIpRule ipRule) + public static Track2Models.IPRule ParseStorageNetworkRuleIPRule(PSIpRule ipRule) { - IPRule returnRule = new IPRule(); + Track2Models.IPRule returnRule = new Track2Models.IPRule(ipRule.IPAddressOrRange); returnRule.Action = ParseStorageNetworkRuleAction(ipRule.Action); - returnRule.IPAddressOrRange = ipRule.IPAddressOrRange; return returnRule; } //Parse single NetworkRule PSResourceAccessRule in SDK to wrapped property PSPSResourceAccessRule - public static PSResourceAccessRule ParsePSResourceAccessRule(ResourceAccessRule rule) + public static PSResourceAccessRule ParsePSResourceAccessRule(Track2Models.ResourceAccessRule rule) { - PSResourceAccessRule returnRule = new PSResourceAccessRule(); - returnRule.TenantId = rule.TenantId; - returnRule.ResourceId = rule.ResourceId; + PSResourceAccessRule returnRule = new PSResourceAccessRule + { + TenantId = rule.TenantId, + ResourceId = rule.ResourceId + }; return returnRule; } //Parse wrapped property PSPSResourceAccessRule to single NetworkRule PSResourceAccessRule in SDK - public static ResourceAccessRule ParseStorageResourceAccessRule(PSResourceAccessRule rule) + public static Track2Models.ResourceAccessRule ParseStorageResourceAccessRule(PSResourceAccessRule rule) { - ResourceAccessRule returnRule = new ResourceAccessRule(); - returnRule.TenantId = rule.TenantId; - returnRule.ResourceId = rule.ResourceId; + Track2Models.ResourceAccessRule returnRule = + new Track2Models.ResourceAccessRule + { + TenantId = rule.TenantId, + ResourceId = rule.ResourceId + }; return returnRule; } //Parse single NetworkRule VirtualNetworkRule in SDK to wrapped property PSVirtualNetworkRule - public static PSVirtualNetworkRule ParsePSNetworkRuleVirtualNetworkRule(VirtualNetworkRule virtualNetworkRule) + public static PSVirtualNetworkRule ParsePSNetworkRuleVirtualNetworkRule(Track2Models.VirtualNetworkRule virtualNetworkRule) { PSVirtualNetworkRule returnRule = new PSVirtualNetworkRule(); returnRule.Action = ParsePSNetworkRuleAction(virtualNetworkRule.Action); @@ -244,30 +251,31 @@ public static PSVirtualNetworkRule ParsePSNetworkRuleVirtualNetworkRule(VirtualN } //Parse wrapped property PSVirtualNetworkRule to single NetworkRule VirtualNetworkRule in SDK - public static VirtualNetworkRule ParseStorageNetworkRuleVirtualNetworkRule(PSVirtualNetworkRule virtualNetworkRule) + public static Track2Models.VirtualNetworkRule ParseStorageNetworkRuleVirtualNetworkRule(PSVirtualNetworkRule virtualNetworkRule) { - VirtualNetworkRule returnRule = new VirtualNetworkRule(); - returnRule.Action = ParseStorageNetworkRuleAction(virtualNetworkRule.Action); - returnRule.VirtualNetworkResourceId = virtualNetworkRule.VirtualNetworkResourceId; + Track2Models.VirtualNetworkRule returnRule = + new Track2Models.VirtualNetworkRule(virtualNetworkRule.VirtualNetworkResourceId); + var action = ParseStorageNetworkRuleAction(virtualNetworkRule.Action); + returnRule.Action = action != null ? action : null; return returnRule; } //Parse Storage NetworkRule object in SDK to wrapped PSNetworkRuleSet - public static PSNetworkRuleSet ParsePSNetworkRule(NetworkRuleSet rules) + public static PSNetworkRuleSet ParsePSNetworkRule(Track2Models.NetworkRuleSet rules) { if (rules == null) { return null; } PSNetworkRuleSet returnRules = new PSNetworkRuleSet(); - returnRules.Bypass = ParsePSNetworkRuleBypass(rules.Bypass); + returnRules.Bypass = rules.Bypass != null ? ParsePSNetworkRuleBypass(rules.Bypass.ToString()) : null; returnRules.DefaultAction = ParsePSNetworkRuleDefaultAction(rules.DefaultAction); List ipRuleList = new List(); - if (rules.IpRules != null) + if (rules.IPRules != null) { - foreach (var ipRule in rules.IpRules) + foreach (var ipRule in rules.IPRules) { ipRuleList.Add(ParsePSNetworkRuleIPRule(ipRule)); } @@ -298,44 +306,40 @@ public static PSNetworkRuleSet ParsePSNetworkRule(NetworkRuleSet rules) } //Parse wrapped PSNetworkRuleSet to storage NetworkRule object in SDK - public static NetworkRuleSet ParseStorageNetworkRule(PSNetworkRuleSet rules) + public static Track2Models.NetworkRuleSet ParseStorageNetworkRule(PSNetworkRuleSet rules) { if (rules == null) { return null; } - NetworkRuleSet returnRules = new NetworkRuleSet(); - returnRules.Bypass = ParseStorageNetworkRuleBypass(rules.Bypass); - returnRules.DefaultAction = ParseStorageNetworkRuleDefaultAction(rules.DefaultAction); + Track2Models.NetworkRuleSet returnRules = + new Track2Models.NetworkRuleSet(ParseStorageNetworkRuleDefaultAction(rules.DefaultAction)) + { + Bypass = ParseStorageNetworkRuleBypass(rules.Bypass) + }; - List ipRuleList = new List(); if (rules.IpRules != null) { foreach (var ipRule in rules.IpRules) { - ipRuleList.Add(ParseStorageNetworkRuleIPRule(ipRule)); + returnRules.IPRules.Add(ParseStorageNetworkRuleIPRule(ipRule)); } - returnRules.IpRules = ipRuleList.ToArray(); } - List virtualNetworkList = new List(); if (rules.VirtualNetworkRules != null) { foreach (var virtualNetworkRule in rules.VirtualNetworkRules) { - virtualNetworkList.Add(ParseStorageNetworkRuleVirtualNetworkRule(virtualNetworkRule)); + returnRules.VirtualNetworkRules.Add(ParseStorageNetworkRuleVirtualNetworkRule(virtualNetworkRule)); } - returnRules.VirtualNetworkRules = virtualNetworkList.ToArray(); } - List resourceAccessRuleList = new List(); if (rules.ResourceAccessRules != null) { foreach (var rule in rules.ResourceAccessRules) { - resourceAccessRuleList.Add(ParseStorageResourceAccessRule(rule)); + returnRules.ResourceAccessRules.Add(ParseStorageResourceAccessRule(rule)); } - returnRules.ResourceAccessRules = resourceAccessRuleList.ToArray(); } return returnRules; diff --git a/src/Storage/Storage.Management/Models/PSRoutingPreference.cs b/src/Storage/Storage.Management/Models/PSRoutingPreference.cs index bfa76016af71..65b30abc75d1 100644 --- a/src/Storage/Storage.Management/Models/PSRoutingPreference.cs +++ b/src/Storage/Storage.Management/Models/PSRoutingPreference.cs @@ -12,7 +12,7 @@ // limitations under the License. // ---------------------------------------------------------------------------------- -using Microsoft.Azure.Management.Storage.Models; +using Track2Models = Azure.ResourceManager.Storage.Models; using System; namespace Microsoft.Azure.Commands.Management.Storage.Models @@ -20,7 +20,7 @@ namespace Microsoft.Azure.Commands.Management.Storage.Models public class PSRoutingPreference { //Parse RoutingPreference in SDK to wrapped property PSRoutingPreference - public static PSRoutingPreference ParsePSRoutingPreference(RoutingPreference routingPreference) + public static PSRoutingPreference ParsePSRoutingPreference(Track2Models.RoutingPreference routingPreference) { if (routingPreference == null) { @@ -29,7 +29,7 @@ public static PSRoutingPreference ParsePSRoutingPreference(RoutingPreference rou PSRoutingPreference pSRoutingPreference = new PSRoutingPreference(); - pSRoutingPreference.RoutingChoice = routingPreference.RoutingChoice; + pSRoutingPreference.RoutingChoice = routingPreference.RoutingChoice != null ? routingPreference.RoutingChoice.ToString() : null; pSRoutingPreference.PublishMicrosoftEndpoints = routingPreference.PublishMicrosoftEndpoints; pSRoutingPreference.PublishInternetEndpoints = routingPreference.PublishInternetEndpoints; diff --git a/src/Storage/Storage.Management/Models/PSStorageAccount.cs b/src/Storage/Storage.Management/Models/PSStorageAccount.cs index 889202dfc399..4d98050c7754 100644 --- a/src/Storage/Storage.Management/Models/PSStorageAccount.cs +++ b/src/Storage/Storage.Management/Models/PSStorageAccount.cs @@ -20,62 +20,71 @@ using System; using System.Collections.Generic; using Microsoft.WindowsAzure.Commands.Common.Attributes; -using StorageModels = Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; +using Track2 = Azure.ResourceManager.Storage; +using Track2Models = Azure.ResourceManager.Storage.Models; +using Azure.ResourceManager.Models; +using Microsoft.WindowsAzure.Commands.Utilities.Common; +using Microsoft.Azure.Storage; +using Microsoft.Azure.Storage.Auth; namespace Microsoft.Azure.Commands.Management.Storage.Models { public class PSStorageAccount : IStorageContextProvider { - public PSStorageAccount(StorageModels.StorageAccount storageAccount) + + public PSStorageAccount(Track2.StorageAccountResource storageAccountResource) { - this.ResourceGroupName = new ResourceIdentifier(storageAccount.Id).ResourceGroupName; - this.StorageAccountName = storageAccount.Name; - this.Id = storageAccount.Id; - this.Location = storageAccount.Location; - this.Sku = new PSSku(storageAccount.Sku); - this.Encryption = storageAccount.Encryption; - this.Kind = storageAccount.Kind; - this.AccessTier = storageAccount.AccessTier; - this.CreationTime = storageAccount.CreationTime; - this.CustomDomain = storageAccount.CustomDomain is null ? null : new PSCustomDomain(storageAccount.CustomDomain); - this.Identity = storageAccount.Identity; - this.LastGeoFailoverTime = storageAccount.LastGeoFailoverTime; - this.PrimaryEndpoints = storageAccount.PrimaryEndpoints; - this.PrimaryLocation = storageAccount.PrimaryLocation; - this.ProvisioningState = storageAccount.ProvisioningState; - this.SecondaryEndpoints = storageAccount.SecondaryEndpoints; - this.SecondaryLocation = storageAccount.SecondaryLocation; - this.StatusOfPrimary = storageAccount.StatusOfPrimary; - this.StatusOfSecondary = storageAccount.StatusOfSecondary; - this.Tags = storageAccount.Tags; - this.EnableHttpsTrafficOnly = storageAccount.EnableHttpsTrafficOnly; - this.NetworkRuleSet = PSNetworkRuleSet.ParsePSNetworkRule(storageAccount.NetworkRuleSet); - this.EnableHierarchicalNamespace = storageAccount.IsHnsEnabled; - this.FailoverInProgress = storageAccount.FailoverInProgress; - this.LargeFileSharesState = storageAccount.LargeFileSharesState; - this.AzureFilesIdentityBasedAuth = storageAccount.AzureFilesIdentityBasedAuthentication is null ? null : new PSAzureFilesIdentityBasedAuthentication(storageAccount.AzureFilesIdentityBasedAuthentication); - this.GeoReplicationStats = PSGeoReplicationStats.ParsePSGeoReplicationStats(storageAccount.GeoReplicationStats); - this.AllowBlobPublicAccess = storageAccount.AllowBlobPublicAccess; - this.MinimumTlsVersion = storageAccount.MinimumTlsVersion; - this.RoutingPreference = PSRoutingPreference.ParsePSRoutingPreference(storageAccount.RoutingPreference); - this.BlobRestoreStatus = storageAccount.BlobRestoreStatus is null ? null : new PSBlobRestoreStatus(storageAccount.BlobRestoreStatus); - this.EnableNfsV3 = storageAccount.EnableNfsV3; - this.ExtendedLocation = storageAccount.ExtendedLocation is null ? null : new PSExtendedLocation(storageAccount.ExtendedLocation); - this.AllowSharedKeyAccess = storageAccount.AllowSharedKeyAccess; - this.KeyCreationTime = storageAccount.KeyCreationTime is null ? null : new PSKeyCreationTime(storageAccount.KeyCreationTime); - this.KeyPolicy = storageAccount.KeyPolicy; - this.SasPolicy = storageAccount.SasPolicy; - this.AllowCrossTenantReplication = storageAccount.AllowCrossTenantReplication; - this.PublicNetworkAccess = storageAccount.PublicNetworkAccess; - this.ImmutableStorageWithVersioning = storageAccount.ImmutableStorageWithVersioning is null ? null : new PSImmutableStorageAccount(storageAccount.ImmutableStorageWithVersioning); - this.StorageAccountSkuConversionStatus = storageAccount.StorageAccountSkuConversionStatus is null ? null : new PSStorageAccountSkuConversionStatus(storageAccount.StorageAccountSkuConversionStatus); + this.ResourceGroupName = new ResourceIdentifier(storageAccountResource.Id).ResourceGroupName; + this.StorageAccountName = storageAccountResource.Data.Name; + this.Id = storageAccountResource.Id; + this.Location = storageAccountResource.Data.Location; + this.Sku = new PSSku(storageAccountResource.Data.Sku); + this.Encryption = storageAccountResource.Data.Encryption; + this.Kind = storageAccountResource.Data.Kind.ToString(); + this.AccessTier = storageAccountResource.Data.AccessTier; + this.CreationTime = storageAccountResource.Data.CreationOn; + this.CustomDomain = storageAccountResource.Data.CustomDomain is null ? null : new PSCustomDomain(storageAccountResource.Data.CustomDomain); + this.Identity = storageAccountResource.Data.Identity != null ? new PSIdentity(storageAccountResource.Data.Identity) : null; + this.LastGeoFailoverTime = storageAccountResource.Data.LastGeoFailoverOn; + this.PrimaryEndpoints = storageAccountResource.Data.PrimaryEndpoints; + this.PrimaryLocation = storageAccountResource.Data.PrimaryLocation; + this.ProvisioningState = storageAccountResource.Data.ProvisioningState; + this.SecondaryEndpoints = storageAccountResource.Data.SecondaryEndpoints; + this.SecondaryLocation = storageAccountResource.Data.SecondaryLocation; + this.StatusOfPrimary = storageAccountResource.Data.StatusOfPrimary; + this.StatusOfSecondary = storageAccountResource.Data.StatusOfSecondary; + this.Tags = storageAccountResource.Data.Tags; + this.EnableHttpsTrafficOnly = storageAccountResource.Data.EnableHttpsTrafficOnly; + + this.NetworkRuleSet = PSNetworkRuleSet.ParsePSNetworkRule(storageAccountResource.Data.NetworkRuleSet); + + this.EnableHierarchicalNamespace = storageAccountResource.Data.IsHnsEnabled; + this.FailoverInProgress = storageAccountResource.Data.FailoverInProgress; + this.LargeFileSharesState = storageAccountResource.Data.LargeFileSharesState.ToString(); + this.AzureFilesIdentityBasedAuth = + storageAccountResource.Data.AzureFilesIdentityBasedAuthentication is null ? null : new PSAzureFilesIdentityBasedAuthentication(storageAccountResource.Data.AzureFilesIdentityBasedAuthentication); + this.GeoReplicationStats = PSGeoReplicationStats.ParsePSGeoReplicationStats(storageAccountResource.Data.GeoReplicationStats); + this.AllowBlobPublicAccess = storageAccountResource.Data.AllowBlobPublicAccess; + this.MinimumTlsVersion = storageAccountResource.Data.MinimumTlsVersion is null ? null : storageAccountResource.Data.MinimumTlsVersion.ToString(); + this.RoutingPreference = PSRoutingPreference.ParsePSRoutingPreference(storageAccountResource.Data.RoutingPreference); + this.BlobRestoreStatus = storageAccountResource.Data.BlobRestoreStatus is null ? null : new PSBlobRestoreStatus(storageAccountResource.Data.BlobRestoreStatus); + this.EnableNfsV3 = storageAccountResource.Data.EnableNfsV3; + this.ExtendedLocation = storageAccountResource.Data.ExtendedLocation is null ? null : new PSExtendedLocation(storageAccountResource.Data.ExtendedLocation); + this.AllowSharedKeyAccess = storageAccountResource.Data.AllowSharedKeyAccess; + this.KeyCreationTime = storageAccountResource.Data.KeyCreationTime is null ? null : new PSKeyCreationTime(storageAccountResource.Data.KeyCreationTime); + this.KeyPolicy = storageAccountResource.Data.KeyExpirationPeriodInDays != null ? new PSKeyPolicy((int)(storageAccountResource.Data.KeyExpirationPeriodInDays)) : null; + this.SasPolicy = storageAccountResource.Data.SasPolicy != null ? new PSSasPolicy(storageAccountResource.Data.SasPolicy.SasExpirationPeriod, storageAccountResource.Data.SasPolicy.ExpirationAction.ToString()) : null; + this.AllowCrossTenantReplication = storageAccountResource.Data.AllowCrossTenantReplication; + this.PublicNetworkAccess = storageAccountResource.Data.PublicNetworkAccess != null ? storageAccountResource.Data.PublicNetworkAccess.ToString() : null; + this.ImmutableStorageWithVersioning = storageAccountResource.Data.ImmutableStorageWithVersioning is null ? null : new PSImmutableStorageAccount(storageAccountResource.Data.ImmutableStorageWithVersioning); } + public bool? AllowCrossTenantReplication { get; set; } public PSKeyCreationTime KeyCreationTime { get; set; } - public KeyPolicy KeyPolicy { get; } - public SasPolicy SasPolicy { get; } + public PSKeyPolicy KeyPolicy { get; } + public PSSasPolicy SasPolicy { get; } [Ps1Xml(Label = "ResourceGroupName", Target = ViewControl.Table, Position = 1)] public string ResourceGroupName { get; set; } @@ -93,35 +102,35 @@ public PSStorageAccount(StorageModels.StorageAccount storageAccount) [Ps1Xml(Label = "Kind", Target = ViewControl.Table, Position = 4)] public string Kind { get; set; } - public Encryption Encryption { get; set; } + public Track2Models.Encryption Encryption { get; set; } [Ps1Xml(Label = "AccessTier", Target = ViewControl.Table, Position = 5)] - public AccessTier? AccessTier { get; set; } + public Track2Models.AccessTier? AccessTier { get; set; } [Ps1Xml(Label = "CreationTime", Target = ViewControl.Table, Position = 6)] - public DateTime? CreationTime { get; set; } + public DateTimeOffset? CreationTime { get; set; } public PSCustomDomain CustomDomain { get; set; } - public Identity Identity { get; set; } + public PSIdentity Identity { get; set; } - public DateTime? LastGeoFailoverTime { get; set; } + public DateTimeOffset? LastGeoFailoverTime { get; set; } - public Endpoints PrimaryEndpoints { get; set; } + public Track2Models.Endpoints PrimaryEndpoints { get; set; } [Ps1Xml(Label = "PrimaryLocation", Target = ViewControl.Table, Position = 2)] public string PrimaryLocation { get; set; } [Ps1Xml(Label = "ProvisioningState", Target = ViewControl.Table, Position = 7)] - public ProvisioningState? ProvisioningState { get; set; } + public Track2Models.ProvisioningState? ProvisioningState { get; set; } - public Endpoints SecondaryEndpoints { get; set; } + public Track2Models.Endpoints SecondaryEndpoints { get; set; } public string SecondaryLocation { get; set; } - public AccountStatus? StatusOfPrimary { get; set; } + public Track2Models.AccountStatus? StatusOfPrimary { get; set; } - public AccountStatus? StatusOfSecondary { get; set; } + public Track2Models.AccountStatus? StatusOfSecondary { get; set; } public IDictionary Tags { get; set; } @@ -157,20 +166,37 @@ public PSStorageAccount(StorageModels.StorageAccount storageAccount) public string PublicNetworkAccess { get; set; } public PSImmutableStorageAccount ImmutableStorageWithVersioning { get; set; } - public PSStorageAccountSkuConversionStatus StorageAccountSkuConversionStatus { get; set; } - - public static PSStorageAccount Create(StorageModels.StorageAccount storageAccount, IStorageManagementClient client) + public static PSStorageAccount Create(Track2.StorageAccountResource storageAccountResource, Track2StorageManagementClient client) { - var result = new PSStorageAccount(storageAccount); + var result = new PSStorageAccount(storageAccountResource); + result.Context = new LazyAzureStorageContext((s) => { - return (new ARMStorageProvider(client)).GetCloudStorageAccount(s, result.ResourceGroupName); + return GetCloudStorageAccount(storageAccountResource); }, result.StorageAccountName) as AzureStorageContext; return result; } + public static CloudStorageAccount GetCloudStorageAccount(Track2.StorageAccountResource storageAccountResource) + { + Uri blobEndpoint = storageAccountResource.Data.PrimaryEndpoints.Blob != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.Blob) : null; + Uri queueEndpoint = storageAccountResource.Data.PrimaryEndpoints.Queue != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.Queue) : null; + Uri tableEndpoint = storageAccountResource.Data.PrimaryEndpoints.Table != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.Table) : null; + Uri fileEndpoint = storageAccountResource.Data.PrimaryEndpoints.File != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.File) : null; + string key = storageAccountResource.GetKeys().Value.Keys[0].Value; + StorageCredentials storageCredentials = new Azure.Storage.Auth.StorageCredentials(storageAccountResource.Data.Name, key); + CloudStorageAccount cloudStorageAccount = new CloudStorageAccount( + storageCredentials, + new StorageUri(blobEndpoint), + new StorageUri(queueEndpoint), + new StorageUri(tableEndpoint), + new StorageUri(fileEndpoint)); + + return cloudStorageAccount; + } + public IStorageContext Context { get; private set; } public IDictionary ExtendedProperties { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -186,45 +212,139 @@ public override string ToString() } } + public class PSKeyPolicy + { + public string KeyExpirationPeriodInDays { get; set; } + + public PSKeyPolicy(int keyExpirationPeriodInDays) + + { + this.KeyExpirationPeriodInDays = keyExpirationPeriodInDays.ToString(); + } + } + + public class PSSasPolicy + { + public string SasExpirationPeriod { get; set; } + + public static string ExpirationAction { get; set; } + + public PSSasPolicy(string sasExpirationPeriod, string expirationAction) + { + if (sasExpirationPeriod != null) + { + this.SasExpirationPeriod = sasExpirationPeriod; + } + if (expirationAction != null) + { + PSSasPolicy.ExpirationAction = expirationAction; + } + + } + + public PSSasPolicy() { } + } + public class PSCustomDomain { public string Name { get; set; } public bool? UseSubDomain { get; set; } - public PSCustomDomain(CustomDomain input) + public PSCustomDomain(Track2Models.CustomDomain input) { this.Name = input.Name; this.UseSubDomain = input.UseSubDomainName; } - public CustomDomain ParseCustomDomain() + public Track2Models.CustomDomain ParseCustomDomain() { - return new CustomDomain(this.Name, this.UseSubDomain); + Track2Models.CustomDomain customDomain = + new Track2Models.CustomDomain(this.Name); + customDomain.UseSubDomainName = this.UseSubDomain; + return customDomain; } } + + + + public class PSIdentity + { + public string PrincipalId { get; set; } + public string TenantId { get; set; } + + public string Type { get; set; } + + public IDictionary UserAssignedIdentities = new Dictionary(); + + public PSIdentity(ManagedServiceIdentity identity) + { + if (identity.PrincipalId != null) + { + this.PrincipalId = identity.PrincipalId.Value.ToString(); + } + + if (identity.TenantId != null) + { + this.TenantId = identity.TenantId.Value.ToString(); + } + if (identity != null) + { + this.Type = identity.ManagedServiceIdentityType.ToString(); + } + + identity.UserAssignedIdentities + .ForEach(x => this.UserAssignedIdentities.Add(x.Key, new PSUserAssignedIdentity(x.Value))); + } + + } + + public class PSUserAssignedIdentity + { + public string PrincipalId { get; set; } + + public string ClientId { get; set; } + + public PSUserAssignedIdentity(global::Azure.ResourceManager.Models.UserAssignedIdentity userAssignedIdentity) + { + if (userAssignedIdentity.PrincipalId != null) + { + this.PrincipalId = userAssignedIdentity.PrincipalId.Value.ToString(); + } + + if (userAssignedIdentity.ClientId != null) + { + this.ClientId = userAssignedIdentity.ClientId.Value.ToString(); + } + } + + } + public class PSSku { public string Name { get; set; } - public SkuTier? Tier { get; set; } + public Track2Models.StorageSkuTier? Tier { get; set; } public string ResourceType { get; set; } public string Kind { get; set; } public IList Locations { get; set; } public IList Capabilities { get; set; } public IList Restrictions { get; set; } - public PSSku(Sku sku) + public PSSku(Track2Models.StorageSku sku) { if (sku != null) { - this.Name = sku.Name; + this.Name = sku.Name.ToString(); this.Tier = sku.Tier; + } } - public Sku ParseSku() + + public Track2Models.StorageSku ParseSku() { - return new Sku(Name, Tier); + Track2Models.StorageSku sku = new Track2Models.StorageSku(Name); + return sku; } } @@ -233,10 +353,10 @@ public class PSExtendedLocation public PSExtendedLocation() { } - public PSExtendedLocation(ExtendedLocation extendedLocation) + public PSExtendedLocation(Track2Models.ExtendedLocation extendedLocation) { this.Name = extendedLocation.Name; - this.Type = extendedLocation.Type; + this.Type = extendedLocation.ExtendedLocationType != null ? extendedLocation.ExtendedLocationType.ToString() : null; } public string Name { get; set; } @@ -248,7 +368,7 @@ public class PSKeyCreationTime public PSKeyCreationTime() { } - public PSKeyCreationTime(KeyCreationTime keyCreationTime) + public PSKeyCreationTime(Track2Models.KeyCreationTime keyCreationTime) { if (keyCreationTime != null) { @@ -256,8 +376,8 @@ public PSKeyCreationTime(KeyCreationTime keyCreationTime) this.Key2 = keyCreationTime.Key2; } } - public System.DateTime? Key1 { get; set; } - public System.DateTime? Key2 { get; set; } + public System.DateTimeOffset? Key1 { get; set; } + public System.DateTimeOffset? Key2 { get; set; } } /// @@ -268,7 +388,7 @@ public class PSImmutableStorageAccount public PSImmutableStorageAccount() { } - public PSImmutableStorageAccount(ImmutableStorageAccount immutableStorageAccount) + public PSImmutableStorageAccount(Track2Models.ImmutableStorageAccount immutableStorageAccount) { if (immutableStorageAccount != null) { @@ -288,37 +408,15 @@ public class PSAccountImmutabilityPolicyProperties public PSAccountImmutabilityPolicyProperties() { } - public PSAccountImmutabilityPolicyProperties(AccountImmutabilityPolicyProperties accountImmutabilityPolicyProperties) + public PSAccountImmutabilityPolicyProperties(Track2Models.AccountImmutabilityPolicyProperties accountImmutabilityPolicyProperties) { if (accountImmutabilityPolicyProperties != null) { this.ImmutabilityPeriodSinceCreationInDays = accountImmutabilityPolicyProperties.ImmutabilityPeriodSinceCreationInDays; - this.State = accountImmutabilityPolicyProperties.State; + this.State = accountImmutabilityPolicyProperties.State != null ? accountImmutabilityPolicyProperties.State.ToString() : null; } } public int? ImmutabilityPeriodSinceCreationInDays { get; set; } public string State { get; set; } } - - /// - /// wrapper class of StorageAccountSkuConversionStatus - /// - public class PSStorageAccountSkuConversionStatus - { - public string SkuConversionStatus { get; set; } - public string TargetSkuName { get; set; } - public string StartTime { get; set; } - public string EndTime { get; set; } - - public PSStorageAccountSkuConversionStatus(StorageAccountSkuConversionStatus status) - { - if (status != null) - { - this.SkuConversionStatus = status.SkuConversionStatus; - this.TargetSkuName = status.TargetSkuName; - this.StartTime = status.StartTime; - this.EndTime = status.EndTime; - } - } - } } diff --git a/src/Storage/Storage.Management/Storage.Management.csproj b/src/Storage/Storage.Management/Storage.Management.csproj index c938fa96f3ba..af2abb9c9c5f 100644 --- a/src/Storage/Storage.Management/Storage.Management.csproj +++ b/src/Storage/Storage.Management/Storage.Management.csproj @@ -14,6 +14,18 @@ $(LegacyAssemblyPrefix)$(PsModuleName) + + + + + + + + + + + + diff --git a/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccount.cs index f253649af99e..a7e9a4a5a0ac 100644 --- a/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccount.cs @@ -12,13 +12,15 @@ // limitations under the License. // ---------------------------------------------------------------------------------- +using Azure; +using Track2 = Azure.ResourceManager.Storage; +using Track2Models = Azure.ResourceManager.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; using Microsoft.Rest.Azure; using System.Management.Automation; + namespace Microsoft.Azure.Commands.Management.Storage { [Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "StorageAccount"), OutputType(typeof(PSStorageAccount))] @@ -88,45 +90,36 @@ public override void ExecuteCmdlet() if (string.IsNullOrEmpty(this.ResourceGroupName)) { - IPage storageAccounts = this.StorageClient.StorageAccounts.List(); - WriteStorageAccountList(storageAccounts); - - while (storageAccounts.NextPageLink != null) + Pageable accounts = this.StorageClientTrack2.ListStorageAccounts(); + foreach (Track2.StorageAccountResource account in accounts) { - storageAccounts = this.StorageClient.StorageAccounts.ListNext(storageAccounts.NextPageLink); - WriteStorageAccountList(storageAccounts); + WriteStorageAccount(account); } } else if (string.IsNullOrEmpty(this.Name)) { - IPage storageAccounts = this.StorageClient.StorageAccounts.ListByResourceGroup(this.ResourceGroupName); - WriteStorageAccountList(storageAccounts); - - while (storageAccounts.NextPageLink != null) + Pageable accounts = this.StorageClientTrack2.ListStorageAccounts(this.ResourceGroupName); + foreach (Track2.StorageAccountResource account in accounts) { - storageAccounts = this.StorageClient.StorageAccounts.ListByResourceGroupNext(storageAccounts.NextPageLink); - WriteStorageAccountList(storageAccounts); + WriteStorageAccount(account); } } else { // ParameterSet ensure can only set one of the following 2 parameters - StorageAccountExpand? expandproperties = null; + Track2Models.StorageAccountExpand? expandProperties = null; if (this.IncludeGeoReplicationStats) { - expandproperties = StorageAccountExpand.GeoReplicationStats; + expandProperties = Track2Models.StorageAccountExpand.GeoReplicationStats; } if (this.IncludeBlobRestoreStatus) { - expandproperties = StorageAccountExpand.BlobRestoreStatus; + expandProperties = Track2Models.StorageAccountExpand.BlobRestoreStatus; } + Track2.StorageAccountResource account = this.StorageClientTrack2.GetSingleStorageAccount( + this.ResourceGroupName, this.Name, expandProperties); - var storageAccount = this.StorageClient.StorageAccounts.GetProperties( - this.ResourceGroupName, - this.Name, - expandproperties); - - WriteStorageAccount(storageAccount); + WriteStorageAccount(account); } } } diff --git a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs index 8399dc796b08..3aeb85b729e6 100644 --- a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs @@ -15,13 +15,16 @@ using System.Collections; using System.Management.Automation; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; -using StorageModels = Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using System; using System.Collections.Generic; +using Track2Models = Azure.ResourceManager.Storage.Models; +using Azure.ResourceManager.Models; +using Azure.Core; +using System.ComponentModel; +using System.Management.Automation.Remoting; +using Azure.ResourceManager.Storage; namespace Microsoft.Azure.Commands.Management.Storage { @@ -62,14 +65,15 @@ public class NewAzureStorageAccountCommand : StorageAccountBaseCmdlet ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Sku Name.")] [Alias(StorageAccountTypeAlias, AccountTypeAlias, Account_TypeAlias)] - [ValidateSet(StorageModels.SkuName.StandardLRS, - StorageModels.SkuName.StandardZRS, - StorageModels.SkuName.StandardGRS, - StorageModels.SkuName.StandardRAGRS, - StorageModels.SkuName.PremiumLRS, - StorageModels.SkuName.PremiumZRS, - StorageModels.SkuName.StandardGZRS, - StorageModels.SkuName.StandardRAGZRS, + [ValidateSet( + SkuNameType.StandardLRS, + SkuNameType.StandardZRS, + SkuNameType.StandardGRS, + SkuNameType.StandardRagrs, + SkuNameType.PremiumLRS, + SkuNameType.PremiumZRS, + SkuNameType.StandardGzrs, + SkuNameType.StandardRagzrs, IgnoreCase = true)] public string SkuName { get; set; } @@ -85,13 +89,14 @@ public class NewAzureStorageAccountCommand : StorageAccountBaseCmdlet [Parameter( Mandatory = false, HelpMessage = "Storage Account Kind.")] - [ValidateSet(StorageModels.Kind.Storage, - StorageModels.Kind.StorageV2, - StorageModels.Kind.BlobStorage, - StorageModels.Kind.BlockBlobStorage, - StorageModels.Kind.FileStorage, + [ValidateSet( + StorageKindType.Storage, + StorageKindType.StorageV2, + StorageKindType.BlobStorage, + StorageKindType.BlockBlobStorage, + StorageKindType.FileStorage, IgnoreCase = true)] - [PSDefaultValue(Help = "StorageV2", Value = StorageModels.Kind.StorageV2)] + [PSDefaultValue(Help = "StorageV2", Value = StorageKindType.StorageV2)] public string Kind { get @@ -103,7 +108,7 @@ public string Kind kind = value; } } - private string kind = StorageModels.Kind.StorageV2; + private string kind = StorageKindType.StorageV2; [Parameter( Mandatory = false, @@ -162,10 +167,10 @@ public bool EnableHttpsTrafficOnly [Parameter( Mandatory = false, HelpMessage = "Set the new Storage Account Identity type, the idenetity is for use with key management services like Azure KeyVault.")] - [ValidateSet(AccountIdentityType.systemAssigned, - AccountIdentityType.userAssigned, - AccountIdentityType.systemAssignedUserAssigned, - AccountIdentityType.none, + [ValidateSet(AccountIdentityType.SystemAssigned, + AccountIdentityType.UserAssigned, + AccountIdentityType.SystemAssignedUserAssigned, + AccountIdentityType.None, IgnoreCase = true)] public string IdentityType { get; set; } @@ -241,8 +246,8 @@ public bool EnableAzureActiveDirectoryDomainServicesForFile [Parameter(Mandatory = false, HelpMessage = "Routing Choice defines the kind of network routing opted by the user. Possible values include: 'MicrosoftRouting', 'InternetRouting'")] [ValidateSet( - Microsoft.Azure.Management.Storage.Models.RoutingChoice.MicrosoftRouting, - Microsoft.Azure.Management.Storage.Models.RoutingChoice.InternetRouting, + RoutingChoiceType.MicrosoftRouting, + RoutingChoiceType.InternalRouting, IgnoreCase = true)] public string RoutingChoice; @@ -360,14 +365,16 @@ public bool EnableActiveDirectoryDomainServicesForFile public SwitchParameter AsJob { get; set; } [Parameter(Mandatory = false, HelpMessage = "Set the Encryption KeyType for Table. -Account, Table will be encrypted with account-scoped encryption key. -Service, Table will always be encrypted with Service-Managed keys. The default value is Service.")] - [ValidateSet(StorageModels.KeyType.Service, - StorageModels.KeyType.Account, + [ValidateSet( + KeyType.Service, + KeyType.Account, IgnoreCase = true)] public string EncryptionKeyTypeForTable { get; set; } [Parameter(Mandatory = false, HelpMessage = "Set the Encryption KeyType for Queue. -Account, Queue will be encrypted with account-scoped encryption key. -Service, Queue will always be encrypted with Service-Managed keys. The default value is Service.")] - [ValidateSet(StorageModels.KeyType.Service, - StorageModels.KeyType.Account, + [ValidateSet( + KeyType.Service, + KeyType.Account, IgnoreCase = true)] public string EncryptionKeyTypeForQueue { get; set; } @@ -379,7 +386,7 @@ public TimeSpan SasExpirationPeriod { get { - return sasExpirationPeriod is null? TimeSpan.Zero : sasExpirationPeriod.Value; + return sasExpirationPeriod is null ? TimeSpan.Zero : sasExpirationPeriod.Value; } set { @@ -422,9 +429,10 @@ public bool AllowBlobPublicAccess [Parameter( Mandatory = false, HelpMessage = "The minimum TLS version to be permitted on requests to storage. The default interpretation is TLS 1.0 for this property.")] - [ValidateSet(StorageModels.MinimumTlsVersion.TLS10, - StorageModels.MinimumTlsVersion.TLS11, - StorageModels.MinimumTlsVersion.TLS12, + [ValidateSet( + MinimumTlsVersionType.TLS10, + MinimumTlsVersionType.TLS11, + MinimumTlsVersionType.TLS12, IgnoreCase = true)] public string MinimumTlsVersion { @@ -543,77 +551,72 @@ public override void ExecuteCmdlet() { base.ExecuteCmdlet(); - CheckNameAvailabilityResult checkNameAvailabilityResult = this.StorageClient.StorageAccounts.CheckNameAvailability(this.Name); + Track2Models.CheckNameAvailabilityResult checkNameAvailabilityResult = + this.StorageClientTrack2.GetSubscription(this.SubscriptionId).CheckStorageAccountNameAvailability( + new Track2Models.StorageAccountCheckNameAvailabilityContent(this.Name)); + if (!checkNameAvailabilityResult.NameAvailable.Value) { throw new System.ArgumentException(checkNameAvailabilityResult.Message, "Name"); } - StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters() - { - Location = this.Location, - Sku = new Sku(this.SkuName), - Tags = TagsConversionHelper.CreateTagDictionary(Tag, validate: true), - }; + Track2Models.StorageKind kind = string.IsNullOrEmpty(this.Kind) ? null : new Track2Models.StorageKind(this.Kind); + + Track2Models.StorageAccountCreateOrUpdateContent createContent = + new Track2Models.StorageAccountCreateOrUpdateContent(new Track2Models.StorageSku(this.SkuName), kind, this.Location); if (this.CustomDomainName != null) { - createParameters.CustomDomain = new CustomDomain() - { - Name = CustomDomainName, - UseSubDomainName = UseSubDomain - }; + + createContent.CustomDomain = new Track2Models.CustomDomain(this.CustomDomainName); + createContent.CustomDomain.UseSubDomainName = this.UseSubDomain; } else if (UseSubDomain != null) { throw new System.ArgumentException(string.Format("UseSubDomain must be set together with CustomDomainName.")); } - if (kind != null) - { - createParameters.Kind = kind; - } - if (this.AccessTier != null) { - createParameters.AccessTier = ParseAccessTier(AccessTier); + createContent.AccessTier = ParseAccessTier(this.AccessTier); } if (enableHttpsTrafficOnly != null) { - createParameters.EnableHttpsTrafficOnly = enableHttpsTrafficOnly; + createContent.EnableHttpsTrafficOnly = enableHttpsTrafficOnly; } if (AssignIdentity.IsPresent || this.UserAssignedIdentityId != null || this.IdentityType != null) { - createParameters.Identity = new Identity() { Type = StorageModels.IdentityType.SystemAssigned }; + createContent.Identity = + new ManagedServiceIdentity(ManagedServiceIdentityType.SystemAssigned); if (this.IdentityType != null) { - createParameters.Identity.Type = GetIdentityTypeString(this.IdentityType); + createContent.Identity.ManagedServiceIdentityType = new ManagedServiceIdentityType(this.IdentityType); } if (this.UserAssignedIdentityId != null) { - if (createParameters.Identity.Type != StorageModels.IdentityType.UserAssigned && createParameters.Identity.Type != StorageModels.IdentityType.SystemAssignedUserAssigned) + if (createContent.Identity.ManagedServiceIdentityType != ManagedServiceIdentityType.UserAssigned && createContent.Identity.ManagedServiceIdentityType != ManagedServiceIdentityType.SystemAssignedUserAssigned) { throw new ArgumentException("UserAssignIdentityId should only be specified when AssignIdentityType is UserAssigned or SystemAssignedUserAssigned.", "UserAssignIdentityId"); } - createParameters.Identity.UserAssignedIdentities = new Dictionary(); - createParameters.Identity.UserAssignedIdentities.Add(this.UserAssignedIdentityId, new UserAssignedIdentity()); + + createContent.Identity.UserAssignedIdentities.Add(new ResourceIdentifier(this.UserAssignedIdentityId), new global::Azure.ResourceManager.Models.UserAssignedIdentity()); + } } if (NetworkRuleSet != null) { - createParameters.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet); + createContent.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet); } if (enableHierarchicalNamespace != null) { - createParameters.IsHnsEnabled = enableHierarchicalNamespace; + createContent.IsHnsEnabled = enableHierarchicalNamespace; } - if (enableAzureActiveDirectoryDomainServicesForFile !=null || enableActiveDirectoryDomainServicesForFile != null) + if (enableAzureActiveDirectoryDomainServicesForFile != null || enableActiveDirectoryDomainServicesForFile != null) { - createParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(); if (enableAzureActiveDirectoryDomainServicesForFile != null && enableAzureActiveDirectoryDomainServicesForFile.Value) { - createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.AADDS; + createContent.AzureFilesIdentityBasedAuthentication = new Track2Models.AzureFilesIdentityBasedAuthentication(Track2Models.DirectoryServiceOptions.Aadds); } else if (enableActiveDirectoryDomainServicesForFile != null && enableActiveDirectoryDomainServicesForFile.Value) { @@ -625,25 +628,23 @@ public override void ExecuteCmdlet() || string.IsNullOrEmpty(this.ActiveDirectoryAzureStorageSid) ) { - throw new System.ArgumentNullException("ActiveDirectoryDomainName, ActiveDirectoryNetBiosDomainName, ActiveDirectoryForestName, ActiveDirectoryDomainGuid, ActiveDirectoryDomainSid, ActiveDirectoryAzureStorageSid", + throw new System.ArgumentNullException("ActiveDirectoryDomainName, ActiveDirectoryNetBiosDomainName, ActiveDirectoryForestName, ActiveDirectoryDomainGuid, ActiveDirectoryDomainSid, ActiveDirectoryAzureStorageSid", "To enable ActiveDirectoryDomainServicesForFile, user must specify all of: ActiveDirectoryDomainName, ActiveDirectoryNetBiosDomainName, ActiveDirectoryForestName, ActiveDirectoryDomainGuid, ActiveDirectoryDomainSid, ActiveDirectoryAzureStorageSid."); } - createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.AD; - createParameters.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties = new ActiveDirectoryProperties() - { - DomainName = this.ActiveDirectoryDomainName, - NetBiosDomainName = this.ActiveDirectoryNetBiosDomainName, - ForestName = this.ActiveDirectoryForestName, - DomainGuid = this.ActiveDirectoryDomainGuid, - DomainSid = this.ActiveDirectoryDomainSid, - AzureStorageSid = this.ActiveDirectoryAzureStorageSid, - SamAccountName = this.ActiveDirectorySamAccountName, - AccountType = this.ActiveDirectoryAccountType - }; + + createContent.AzureFilesIdentityBasedAuthentication = + new Track2Models.AzureFilesIdentityBasedAuthentication(Track2Models.DirectoryServiceOptions.AD); + createContent.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties = + new Track2Models.ActiveDirectoryProperties(this.ActiveDirectoryDomainName, this.ActiveDirectoryNetBiosDomainName, + this.ActiveDirectoryForestName, this.ActiveDirectoryDomainGuid, this.ActiveDirectoryDomainSid, this.ActiveDirectoryAzureStorageSid); + createContent.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties.SamAccountName = this.ActiveDirectorySamAccountName; + createContent.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties.AccountType = this.ActiveDirectoryAccountType; + } else { - createParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.None; + createContent.AzureFilesIdentityBasedAuthentication = + new Track2Models.AzureFilesIdentityBasedAuthentication(Track2Models.DirectoryServiceOptions.None); } } @@ -653,52 +654,64 @@ public override void ExecuteCmdlet() { throw new ArgumentException("'-DefaultSharePermission' need be specify together with '-EnableAzureActiveDirectoryDomainServicesForFile' or '-EnableActiveDirectoryDomainServicesForFile'."); } - if (createParameters.AzureFilesIdentityBasedAuthentication == null) + if (createContent.AzureFilesIdentityBasedAuthentication == null) { - createParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(); + createContent.AzureFilesIdentityBasedAuthentication = + new Track2Models.AzureFilesIdentityBasedAuthentication(Track2Models.DirectoryServiceOptions.None); } - createParameters.AzureFilesIdentityBasedAuthentication.DefaultSharePermission = this.DefaultSharePermission; + + createContent.AzureFilesIdentityBasedAuthentication.DefaultSharePermission = this.DefaultSharePermission; } if (this.EnableLargeFileShare.IsPresent) { - createParameters.LargeFileSharesState = LargeFileSharesState.Enabled; + createContent.LargeFileSharesState = Track2Models.LargeFileSharesState.Enabled; } - if(this.EncryptionKeyTypeForQueue != null || this.EncryptionKeyTypeForTable != null || this.RequireInfrastructureEncryption.IsPresent) + if (this.EncryptionKeyTypeForQueue != null || this.EncryptionKeyTypeForTable != null || this.RequireInfrastructureEncryption.IsPresent) { - createParameters.Encryption = new Encryption(); - createParameters.Encryption.KeySource = KeySource.MicrosoftStorage; + + createContent.Encryption = new Track2Models.Encryption(Track2Models.KeySource.MicrosoftStorage); + if (this.EncryptionKeyTypeForQueue != null || this.EncryptionKeyTypeForTable != null) { - createParameters.Encryption.Services = new EncryptionServices(); + createContent.Encryption.Services = new Track2Models.EncryptionServices(); + if (this.EncryptionKeyTypeForQueue != null) { - createParameters.Encryption.Services.Queue = new EncryptionService(keyType: this.EncryptionKeyTypeForQueue); + createContent.Encryption.Services.Queue = new Track2Models.EncryptionService + { + KeyType = this.EncryptionKeyTypeForQueue + }; } if (this.EncryptionKeyTypeForTable != null) { - createParameters.Encryption.Services.Table = new EncryptionService(keyType: this.EncryptionKeyTypeForTable); + createContent.Encryption.Services.Table = new Track2Models.EncryptionService + { + KeyType = this.EncryptionKeyTypeForTable + }; } } if (this.RequireInfrastructureEncryption.IsPresent) { - createParameters.Encryption.RequireInfrastructureEncryption = true; - if (createParameters.Encryption.Services is null) + createContent.Encryption.RequireInfrastructureEncryption = true; + + if (createContent.Encryption.Services == null) { - createParameters.Encryption.Services = new EncryptionServices(); - createParameters.Encryption.Services.Blob = new EncryptionService(); + createContent.Encryption.Services = new Track2Models.EncryptionServices(); + createContent.Encryption.Services.Blob = new Track2Models.EncryptionService(); } + } } - if (this.KeyVaultUri !=null || this.KeyName != null || this.KeyVersion != null || this.KeyVaultUserAssignedIdentityId != null) + if (this.KeyVaultUri != null || this.KeyName != null || this.KeyVersion != null || this.KeyVaultUserAssignedIdentityId != null) { if ((this.KeyVaultUri != null && this.KeyName == null) || (this.KeyVaultUri == null && this.KeyName != null)) { - throw new ArgumentException("KeyVaultUri and KeyName must be specify together"); + throw new ArgumentException("KeyVaultUri and KeyName must be specify together"); } if (this.KeyVersion != null && (this.KeyVaultUri == null || this.KeyName == null)) { - throw new ArgumentException("KeyVersion can only be specified when specify KeyVaultUri and KeyName together.", "KeyVersion"); + throw new ArgumentException("KeyVersion can only be specified when specify KeyVaultUri and KeyName together.", "KeyVersion"); } if (this.KeyVaultUserAssignedIdentityId != null && (this.KeyVaultUri == null || this.KeyName == null)) @@ -706,98 +719,124 @@ public override void ExecuteCmdlet() throw new ArgumentException("KeyVaultUserAssignedIdentityId can only be specified when specify KeyVaultUri and KeyName together.", "KeyVaultUserAssignedIdentityId"); } - if (createParameters.Encryption == null) + + if (createContent.Encryption == null) { - createParameters.Encryption = new Encryption(); - createParameters.Encryption.KeySource = KeySource.MicrosoftStorage; + createContent.Encryption = new Track2Models.Encryption( + Track2Models.KeySource.MicrosoftStorage); } - if (createParameters.Encryption.Services is null) + + if (createContent.Encryption.Services == null) { - createParameters.Encryption.Services = new EncryptionServices(); - createParameters.Encryption.Services.Blob = new EncryptionService(); + createContent.Encryption.Services = new Track2Models.EncryptionServices + { + Blob = new Track2Models.EncryptionService() + }; } + if (this.KeyVaultUri != null || this.KeyName != null || this.KeyVersion != null) { - createParameters.Encryption.KeySource = KeySource.MicrosoftKeyvault; - createParameters.Encryption.KeyVaultProperties = new KeyVaultProperties(this.KeyName, this.KeyVersion, this.KeyVaultUri); + + createContent.Encryption.KeySource = Track2Models.KeySource.MicrosoftKeyvault; + createContent.Encryption.KeyVaultProperties = new Track2Models.KeyVaultProperties + { + KeyName = this.KeyName, + KeyVersion = this.KeyVersion, + KeyVaultUri = new Uri(this.KeyVaultUri) + }; } if (this.KeyVaultUserAssignedIdentityId != null) { - createParameters.Encryption.EncryptionIdentity = new EncryptionIdentity(); - createParameters.Encryption.EncryptionIdentity.EncryptionUserAssignedIdentity = this.KeyVaultUserAssignedIdentityId; + createContent.Encryption.EncryptionIdentity = new Track2Models.EncryptionIdentity + { + EncryptionUserAssignedIdentity = this.KeyVaultUserAssignedIdentityId + }; + } } if (this.minimumTlsVersion != null) { - createParameters.MinimumTlsVersion = this.minimumTlsVersion; + createContent.MinimumTlsVersion = new Track2Models.MinimumTlsVersion(this.minimumTlsVersion); } if (this.allowBlobPublicAccess != null) { - createParameters.AllowBlobPublicAccess = this.allowBlobPublicAccess; + createContent.AllowBlobPublicAccess = this.allowBlobPublicAccess; } if (this.RoutingChoice != null || this.publishMicrosoftEndpoint != null || this.publishInternetEndpoint != null) { - createParameters.RoutingPreference = new RoutingPreference(this.RoutingChoice, this.publishMicrosoftEndpoint, this.publishInternetEndpoint); + createContent.RoutingPreference = new Track2Models.RoutingPreference + { + RoutingChoice = new Track2Models.RoutingChoice(this.RoutingChoice), + PublishMicrosoftEndpoints = this.publishMicrosoftEndpoint, + PublishInternetEndpoints = this.publishInternetEndpoint + }; } if (allowSharedKeyAccess != null) { - createParameters.AllowSharedKeyAccess = allowSharedKeyAccess; + createContent.AllowSharedKeyAccess = this.allowSharedKeyAccess; } if (enableNfsV3 != null) { - createParameters.EnableNfsV3 = enableNfsV3; + createContent.EnableNfsV3 = this.enableNfsV3; } if (this.EdgeZone != null) { - createParameters.ExtendedLocation = new ExtendedLocation() + createContent.ExtendedLocation = new Track2Models.ExtendedLocation { - Type = ExtendedLocationTypes.EdgeZone, - Name = this.EdgeZone + Name = this.EdgeZone, + ExtendedLocationType = Track2Models.ExtendedLocationTypes.EdgeZone, }; } if (sasExpirationPeriod != null) { - createParameters.SasPolicy = new SasPolicy(sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss")); + createContent.SasPolicy = new Track2Models.SasPolicy(sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss"), null); + } if (keyExpirationPeriodInDay != null) { - createParameters.KeyPolicy = new KeyPolicy(keyExpirationPeriodInDay.Value); + createContent.KeyExpirationPeriodInDays = keyExpirationPeriodInDay.Value; + } - if(allowCrossTenantReplication != null) + if (allowCrossTenantReplication != null) { - createParameters.AllowCrossTenantReplication = allowCrossTenantReplication; + createContent.AllowCrossTenantReplication = this.allowCrossTenantReplication; } if (this.PublicNetworkAccess != null) { - createParameters.PublicNetworkAccess = this.PublicNetworkAccess; + createContent.PublicNetworkAccess = this.PublicNetworkAccess; } - if (EnableAccountLevelImmutability.IsPresent || this.immutabilityPeriod != null || this.ImmutabilityPolicyState != null) + if (EnableAccountLevelImmutability.IsPresent || this.immutabilityPeriod != null || this.ImmutabilityPolicyState != null) { if (!EnableAccountLevelImmutability.IsPresent) { throw new ArgumentException("ImmutabilityPeriod, ImmutabilityPolicyState and AllowProtectedAppendWrite, can only be specified with -EnableAccountLevelImmutability."); } - createParameters.ImmutableStorageWithVersioning = new ImmutableStorageAccount(); - createParameters.ImmutableStorageWithVersioning.Enabled = this.EnableAccountLevelImmutability.IsPresent; + + createContent.ImmutableStorageWithVersioning = new Track2Models.ImmutableStorageAccount + { + Enabled = this.EnableAccountLevelImmutability.IsPresent + }; + + if (this.immutabilityPeriod != null || this.ImmutabilityPolicyState != null) { - createParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy = new AccountImmutabilityPolicyProperties(); - createParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays = this.immutabilityPeriod; - createParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy.State = this.ImmutabilityPolicyState; + createContent.ImmutableStorageWithVersioning.ImmutabilityPolicy = new Track2Models.AccountImmutabilityPolicyProperties + { + ImmutabilityPeriodSinceCreationInDays = this.ImmutabilityPeriod, + State = this.ImmutabilityPolicyState, + }; + } } - var createAccountResponse = this.StorageClient.StorageAccounts.Create( - this.ResourceGroupName, - this.Name, - createParameters); + var createAccountResponse = this.StorageClientTrack2.CreateStorageAccount(this.ResourceGroupName, this.Name, createContent); + var storageAccount = this.StorageClientTrack2.GetSingleStorageAccount(this.ResourceGroupName, this.Name); - var storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); + WriteStorageAccount(storageAccount); - this.WriteStorageAccount(storageAccount); } } } diff --git a/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccount.cs index d3302b8c3619..bac84078e813 100644 --- a/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccount.cs @@ -13,8 +13,8 @@ // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; -using Microsoft.Azure.Management.Storage; using System.Management.Automation; +using Azure; namespace Microsoft.Azure.Commands.Management.Storage { @@ -56,9 +56,7 @@ public override void ExecuteCmdlet() { if (this.Force || ShouldContinue(string.Format("Remove Storage Account '{0}' and all content in it", this.Name), "")) { - this.StorageClient.StorageAccounts.Delete( - this.ResourceGroupName, - this.Name); + this.StorageClientTrack2.GetStorageAccount(this.ResourceGroupName, this.Name).Delete(WaitUntil.Completed); } } } diff --git a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs index 6ca2af72787f..a68f03e11c51 100644 --- a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs @@ -16,12 +16,13 @@ using System.Collections.Generic; using System.Management.Automation; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; -using StorageModels = Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using System; +using Track2 = Azure.ResourceManager.Models; +using Track2Models = Azure.ResourceManager.Storage.Models; +using Microsoft.WindowsAzure.Commands.Utilities.Common; +using Azure.Core; namespace Microsoft.Azure.Commands.Management.Storage { @@ -78,13 +79,14 @@ public SwitchParameter Force ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Sku Name.")] [Alias(StorageAccountTypeAlias, AccountTypeAlias, Account_TypeAlias)] - [ValidateSet(StorageModels.SkuName.StandardLRS, - StorageModels.SkuName.StandardZRS, - StorageModels.SkuName.StandardGRS, - StorageModels.SkuName.StandardRAGRS, - StorageModels.SkuName.PremiumLRS, - StorageModels.SkuName.StandardGZRS, - StorageModels.SkuName.StandardRAGZRS, + [ValidateSet( + SkuNameType.StandardLRS, + SkuNameType.StandardZRS, + SkuNameType.StandardGRS, + SkuNameType.StandardRagrs, + SkuNameType.PremiumLRS, + SkuNameType.StandardGzrs, + SkuNameType.StandardRagzrs, IgnoreCase = true)] public string SkuName { get; set; } @@ -192,10 +194,10 @@ public string KeyVaultUri [Parameter( Mandatory = false, HelpMessage = "Set the new Storage Account Identity type, the idenetity is for use with key management services like Azure KeyVault.")] - [ValidateSet(AccountIdentityType.systemAssigned, - AccountIdentityType.userAssigned, - AccountIdentityType.systemAssignedUserAssigned, - AccountIdentityType.none, + [ValidateSet(AccountIdentityType.SystemAssigned, + AccountIdentityType.UserAssigned, + AccountIdentityType.SystemAssignedUserAssigned, + AccountIdentityType.None, IgnoreCase = true)] public string IdentityType { get; set; } @@ -239,8 +241,8 @@ public bool EnableAzureActiveDirectoryDomainServicesForFile [Parameter(Mandatory = false, HelpMessage = "Routing Choice defines the kind of network routing opted by the user. Possible values include: 'MicrosoftRouting', 'InternetRouting'")] [ValidateSet( - Microsoft.Azure.Management.Storage.Models.RoutingChoice.MicrosoftRouting, - Microsoft.Azure.Management.Storage.Models.RoutingChoice.InternetRouting, + RoutingChoiceType.MicrosoftRouting, + RoutingChoiceType.InternalRouting, IgnoreCase = true)] [ValidateNotNullOrEmpty] public string RoutingChoice; @@ -261,7 +263,7 @@ public bool PublishMicrosoftEndpoint } } private bool? publishMicrosoftEndpoint = null; - + [Parameter( Mandatory = false, HelpMessage = "Indicates whether internet routing storage endpoints are to be published")] @@ -278,7 +280,7 @@ public bool PublishInternetEndpoint } } private bool? publishInternetEndpoint = null; - + [Parameter( Mandatory = true, HelpMessage = "Enable Azure Files Active Directory Domain Service Authentication for the storage account.", @@ -374,9 +376,10 @@ public bool AllowBlobPublicAccess [Parameter( Mandatory = false, HelpMessage = "The minimum TLS version to be permitted on requests to storage.")] - [ValidateSet(StorageModels.MinimumTlsVersion.TLS10, - StorageModels.MinimumTlsVersion.TLS11, - StorageModels.MinimumTlsVersion.TLS12, + [ValidateSet( + MinimumTlsVersionType.TLS10, + MinimumTlsVersionType.TLS11, + MinimumTlsVersionType.TLS12, IgnoreCase = true)] public string MinimumTlsVersion { @@ -389,7 +392,7 @@ public string MinimumTlsVersion minimumTlsVersion = value; } } - private string minimumTlsVersion = null; + private string minimumTlsVersion = null; [Parameter( Mandatory = false, @@ -508,25 +511,25 @@ public override void ExecuteCmdlet() { if (this.force || this.AccessTier == null || ShouldContinue("Changing the access tier may result in additional charges. See (http://go.microsoft.com/fwlink/?LinkId=786482) to learn more.", "")) { - StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters(); + + Track2Models.StorageAccountPatch storageAccountPatch = new Track2Models.StorageAccountPatch(); + if (this.SkuName != null) { - updateParameters.Sku = new Sku(this.SkuName); + storageAccountPatch.Sku = new Track2Models.StorageSku(new Track2Models.StorageSkuName(this.SkuName)); } if (this.Tag != null) { Dictionary tagDictionary = TagsConversionHelper.CreateTagDictionary(Tag, validate: true); - updateParameters.Tags = tagDictionary ?? new Dictionary(); + tagDictionary.ForEach(kv => storageAccountPatch.Tags.Add(kv.Key, kv.Value)); } if (this.CustomDomainName != null) { - updateParameters.CustomDomain = new CustomDomain() - { - Name = CustomDomainName, - UseSubDomainName = UseSubDomain - }; + storageAccountPatch.CustomDomain = new Track2Models.CustomDomain(this.CustomDomainName); + storageAccountPatch.CustomDomain.UseSubDomainName = this.UseSubDomain; + } else if (UseSubDomain != null) { @@ -535,40 +538,43 @@ public override void ExecuteCmdlet() if (this.AccessTier != null) { - updateParameters.AccessTier = ParseAccessTier(AccessTier); + storageAccountPatch.AccessTier = ParseAccessTier(this.AccessTier); } if (enableHttpsTrafficOnly != null) { - updateParameters.EnableHttpsTrafficOnly = enableHttpsTrafficOnly; + storageAccountPatch.EnableHttpsTrafficOnly = enableHttpsTrafficOnly; } if (AssignIdentity.IsPresent || this.UserAssignedIdentityId != null || this.IdentityType != null) { - updateParameters.Identity = new Identity() { Type = StorageModels.IdentityType.SystemAssigned }; + storageAccountPatch.Identity = new Track2.ManagedServiceIdentity(Track2.ManagedServiceIdentityType.SystemAssigned); if (this.IdentityType != null) { - updateParameters.Identity.Type = GetIdentityTypeString(this.IdentityType); + storageAccountPatch.Identity.ManagedServiceIdentityType = new Track2.ManagedServiceIdentityType(this.IdentityType); } if (this.UserAssignedIdentityId != null) { - if (updateParameters.Identity.Type != StorageModels.IdentityType.UserAssigned && updateParameters.Identity.Type != StorageModels.IdentityType.SystemAssignedUserAssigned) + if (storageAccountPatch.Identity.ManagedServiceIdentityType != Track2.ManagedServiceIdentityType.UserAssigned && storageAccountPatch.Identity.ManagedServiceIdentityType != Track2.ManagedServiceIdentityType.SystemAssignedUserAssigned) { throw new ArgumentException("UserAssignIdentityId should only be specified when AssignIdentityType is UserAssigned or SystemAssignedUserAssigned.", "UserAssignIdentityId"); } - updateParameters.Identity.UserAssignedIdentities = new Dictionary(); - updateParameters.Identity.UserAssignedIdentities.Add(this.UserAssignedIdentityId, new UserAssignedIdentity()); - var accountProperties = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); - if (accountProperties.Identity != null && accountProperties.Identity.UserAssignedIdentities != null && accountProperties.Identity.UserAssignedIdentities.Count > 0) + storageAccountPatch.Identity.UserAssignedIdentities.Add(new ResourceIdentifier(this.UserAssignedIdentityId), new global::Azure.ResourceManager.Models.UserAssignedIdentity()); + + var accountProperties = this.StorageClientTrack2.GetSingleStorageAccount(this.ResourceGroupName, this.Name); + + + if (accountProperties.Data.Identity != null && accountProperties.Data.Identity.UserAssignedIdentities != null && accountProperties.Data.Identity.UserAssignedIdentities.Count > 0) { - foreach (var uid in accountProperties.Identity.UserAssignedIdentities) + foreach (var uid in accountProperties.Data.Identity.UserAssignedIdentities) { - if (!uid.Key.Equals(this.UserAssignedIdentityId, StringComparison.OrdinalIgnoreCase)) + if (!uid.Key.ToString().Equals(this.UserAssignedIdentityId, StringComparison.OrdinalIgnoreCase)) { - updateParameters.Identity.UserAssignedIdentities.Add(uid.Key, null); + storageAccountPatch.Identity.UserAssignedIdentities.Add(uid.Key, null); } } } + } } @@ -578,50 +584,61 @@ public override void ExecuteCmdlet() { keyvaultEncryption = true; } - updateParameters.Encryption = ParseEncryption(StorageEncryption, keyvaultEncryption, KeyName, KeyVersion, KeyVaultUri); + + storageAccountPatch.Encryption = ParseEncryption(StorageEncryption, keyvaultEncryption, KeyName, KeyVersion, KeyVaultUri); + if (this.KeyVaultUserAssignedIdentityId != null) { - updateParameters.Encryption.EncryptionIdentity = new EncryptionIdentity(); - updateParameters.Encryption.EncryptionIdentity.EncryptionUserAssignedIdentity = this.KeyVaultUserAssignedIdentityId; + storageAccountPatch.Encryption.EncryptionIdentity = new Track2Models.EncryptionIdentity + { + EncryptionUserAssignedIdentity = this.KeyVaultUserAssignedIdentityId + }; } } - + if (NetworkRuleSet != null) { - updateParameters.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet); + storageAccountPatch.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet); } if (UpgradeToStorageV2.IsPresent) { - updateParameters.Kind = Kind.StorageV2; + storageAccountPatch.Kind = Track2Models.StorageKind.StorageV2; } if (enableAzureActiveDirectoryDomainServicesForFile != null) { if (enableAzureActiveDirectoryDomainServicesForFile.Value) // enable AADDS { //if user want to enable AADDS, must first disable AD - var originStorageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); - if (originStorageAccount.AzureFilesIdentityBasedAuthentication != null - && originStorageAccount.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions == DirectoryServiceOptions.AD) + + var originStorageAccount = this.StorageClientTrack2.GetSingleStorageAccount(this.ResourceGroupName, this.Name); + + if (originStorageAccount.Data.AzureFilesIdentityBasedAuthentication != null + && originStorageAccount.Data.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions == Track2Models.DirectoryServiceOptions.AD) { throw new System.ArgumentException("The Storage account already enabled ActiveDirectoryDomainServicesForFile, please disable it by run this cmdlets with \"-EnableActiveDirectoryDomainServicesForFile $false\" before enable AzureActiveDirectoryDomainServicesForFile."); } - updateParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(); - updateParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.AADDS; + + storageAccountPatch.AzureFilesIdentityBasedAuthentication = + new Track2Models.AzureFilesIdentityBasedAuthentication(Track2Models.DirectoryServiceOptions.Aadds); + } else //Disable AADDS { // Only disable AADDS; else keep unchanged - var originStorageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); - if (originStorageAccount.AzureFilesIdentityBasedAuthentication == null - || originStorageAccount.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions == DirectoryServiceOptions.AADDS) + + var originStorageAccount = this.StorageClientTrack2.GetSingleStorageAccount(this.ResourceGroupName, this.Name); + + if (originStorageAccount.Data.AzureFilesIdentityBasedAuthentication == null + || originStorageAccount.Data.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions == Track2Models.DirectoryServiceOptions.Aadds) { - updateParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(); - updateParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.None; + storageAccountPatch.AzureFilesIdentityBasedAuthentication = + new Track2Models.AzureFilesIdentityBasedAuthentication(Track2Models.DirectoryServiceOptions.None); } else { - updateParameters.AzureFilesIdentityBasedAuthentication = originStorageAccount.AzureFilesIdentityBasedAuthentication; + storageAccountPatch.AzureFilesIdentityBasedAuthentication = originStorageAccount.Data.AzureFilesIdentityBasedAuthentication; + } } } @@ -643,26 +660,26 @@ public override void ExecuteCmdlet() } //if user want to enable AD, must first disable AADDS - var originStorageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); - if (originStorageAccount.AzureFilesIdentityBasedAuthentication != null - && originStorageAccount.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions == DirectoryServiceOptions.AADDS) + + var originStorageAccount = this.StorageClientTrack2.GetSingleStorageAccount(this.ResourceGroupName, this.Name); + + + + if (originStorageAccount.Data.AzureFilesIdentityBasedAuthentication != null + && originStorageAccount.Data.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions == Track2Models.DirectoryServiceOptions.Aadds) { throw new System.ArgumentException("The Storage account already enabled AzureActiveDirectoryDomainServicesForFile, please disable it by run this cmdlets with \"-EnableAzureActiveDirectoryDomainServicesForFile $false\" before enable ActiveDirectoryDomainServicesForFile."); } - updateParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(); - updateParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.AD; - updateParameters.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties = new ActiveDirectoryProperties() - { - DomainName = this.ActiveDirectoryDomainName, - NetBiosDomainName = this.ActiveDirectoryNetBiosDomainName, - ForestName = this.ActiveDirectoryForestName, - DomainGuid = this.ActiveDirectoryDomainGuid, - DomainSid = this.ActiveDirectoryDomainSid, - AzureStorageSid = this.ActiveDirectoryAzureStorageSid, - SamAccountName = this.ActiveDirectorySamAccountName, - AccountType = this.ActiveDirectoryAccountType - }; + storageAccountPatch.AzureFilesIdentityBasedAuthentication = + new Track2Models.AzureFilesIdentityBasedAuthentication(Track2Models.DirectoryServiceOptions.AD); + + storageAccountPatch.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties = + new Track2Models.ActiveDirectoryProperties(this.ActiveDirectoryDomainName, this.ActiveDirectoryNetBiosDomainName, + this.ActiveDirectoryForestName, this.ActiveDirectoryDomainGuid, this.ActiveDirectoryDomainSid, this.ActiveDirectoryAzureStorageSid); + storageAccountPatch.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties.SamAccountName = this.ActiveDirectorySamAccountName; + storageAccountPatch.AzureFilesIdentityBasedAuthentication.ActiveDirectoryProperties.AccountType = this.ActiveDirectoryAccountType; + } else // Disable AD { @@ -680,77 +697,93 @@ public override void ExecuteCmdlet() } // Only disable AD; else keep unchanged - var originStorageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); - if (originStorageAccount.AzureFilesIdentityBasedAuthentication == null - || originStorageAccount.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions == DirectoryServiceOptions.AD) + var originStorageAccount = this.StorageClientTrack2.GetSingleStorageAccount(this.ResourceGroupName, this.Name); + + if (originStorageAccount.Data.AzureFilesIdentityBasedAuthentication == null + || originStorageAccount.Data.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions == Track2Models.DirectoryServiceOptions.AD) { - updateParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(); - updateParameters.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions = DirectoryServiceOptions.None; + storageAccountPatch.AzureFilesIdentityBasedAuthentication = + new Track2Models.AzureFilesIdentityBasedAuthentication(Track2Models.DirectoryServiceOptions.AD); + } else { - updateParameters.AzureFilesIdentityBasedAuthentication = originStorageAccount.AzureFilesIdentityBasedAuthentication; + storageAccountPatch.AzureFilesIdentityBasedAuthentication = originStorageAccount.Data.AzureFilesIdentityBasedAuthentication; + } } } if (this.DefaultSharePermission != null) { - if (updateParameters.AzureFilesIdentityBasedAuthentication == null) + if (storageAccountPatch.AzureFilesIdentityBasedAuthentication == null) { - updateParameters.AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(); + storageAccountPatch.AzureFilesIdentityBasedAuthentication = + new Track2Models.AzureFilesIdentityBasedAuthentication( + Track2Models.DirectoryServiceOptions.None); } - updateParameters.AzureFilesIdentityBasedAuthentication.DefaultSharePermission = this.DefaultSharePermission; + + storageAccountPatch.AzureFilesIdentityBasedAuthentication.DefaultSharePermission = this.DefaultSharePermission; } if (this.EnableLargeFileShare.IsPresent) { - updateParameters.LargeFileSharesState = LargeFileSharesState.Enabled; + storageAccountPatch.LargeFileSharesState = Track2Models.LargeFileSharesState.Enabled; } if (this.minimumTlsVersion != null) { - updateParameters.MinimumTlsVersion = this.minimumTlsVersion; + storageAccountPatch.MinimumTlsVersion = this.minimumTlsVersion; } if (this.allowBlobPublicAccess != null) { - updateParameters.AllowBlobPublicAccess = this.allowBlobPublicAccess; + storageAccountPatch.AllowBlobPublicAccess = this.allowBlobPublicAccess; } if (this.RoutingChoice != null || this.publishMicrosoftEndpoint != null || this.publishInternetEndpoint != null) - { - updateParameters.RoutingPreference = new RoutingPreference(this.RoutingChoice, this.publishMicrosoftEndpoint, this.publishInternetEndpoint); + { + storageAccountPatch.RoutingPreference = new Track2Models.RoutingPreference + { + RoutingChoice = this.RoutingChoice, + PublishInternetEndpoints = this.publishInternetEndpoint, + PublishMicrosoftEndpoints = this.publishMicrosoftEndpoint, + + }; } if (allowSharedKeyAccess != null) { - updateParameters.AllowSharedKeyAccess = allowSharedKeyAccess; + storageAccountPatch.AllowSharedKeyAccess = this.allowSharedKeyAccess; } if (sasExpirationPeriod != null) { - updateParameters.SasPolicy = new SasPolicy(sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss")); + storageAccountPatch.SasPolicy = new Track2Models.SasPolicy( + this.sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss"), null); } if (keyExpirationPeriodInDay != null) { - updateParameters.KeyPolicy = new KeyPolicy(keyExpirationPeriodInDay.Value); + + storageAccountPatch.KeyExpirationPeriodInDays = keyExpirationPeriodInDay.Value; + + } if (allowCrossTenantReplication != null) { - updateParameters.AllowCrossTenantReplication = allowCrossTenantReplication; + storageAccountPatch.AllowCrossTenantReplication = this.allowCrossTenantReplication; } if (this.PublicNetworkAccess != null) { - updateParameters.PublicNetworkAccess = this.PublicNetworkAccess; + storageAccountPatch.PublicNetworkAccess = this.PublicNetworkAccess; } - if(this.immutabilityPeriod !=null || this.ImmutabilityPolicyState != null) + if (this.immutabilityPeriod != null || this.ImmutabilityPolicyState != null) { - updateParameters.ImmutableStorageWithVersioning = new ImmutableStorageAccount(); - updateParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy = new AccountImmutabilityPolicyProperties(); - updateParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays = this.immutabilityPeriod; - updateParameters.ImmutableStorageWithVersioning.ImmutabilityPolicy.State = this.ImmutabilityPolicyState; + storageAccountPatch.ImmutableStorageWithVersioning = new Track2Models.ImmutableStorageAccount(); + storageAccountPatch.ImmutableStorageWithVersioning.ImmutabilityPolicy = new Track2Models.AccountImmutabilityPolicyProperties + { + ImmutabilityPeriodSinceCreationInDays = this.immutabilityPeriod, + State = this.ImmutabilityPolicyState, + }; + } - var updatedAccountResponse = this.StorageClient.StorageAccounts.Update( - this.ResourceGroupName, - this.Name, - updateParameters); - var storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); + var updatedAccountResponse = this.StorageClientTrack2.UpdateStorageAccount(this.ResourceGroupName, this.Name, storageAccountPatch); + var storageAccount = this.StorageClientTrack2.GetSingleStorageAccount(this.ResourceGroupName, this.Name, null); WriteStorageAccount(storageAccount); } diff --git a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs index 998d0583315a..ecb6365fc9f8 100644 --- a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs +++ b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs @@ -12,6 +12,11 @@ // limitations under the License. // ---------------------------------------------------------------------------------- +using Azure.Core; +using Azure.ResourceManager; +using Azure.ResourceManager.Resources; +using Track2 = Azure.ResourceManager.Storage; +using Track2Models = Azure.ResourceManager.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.Azure.Management.Storage; @@ -73,12 +78,53 @@ protected struct ManagementPolicyAction protected struct AccountIdentityType { - internal const string systemAssigned = "SystemAssigned"; - internal const string userAssigned = "UserAssigned"; - internal const string systemAssignedUserAssigned = "SystemAssignedUserAssigned"; - internal const string none = "None"; + internal const string SystemAssigned = "SystemAssigned"; + internal const string UserAssigned = "UserAssigned"; + internal const string SystemAssignedUserAssigned = "SystemAssignedUserAssigned"; + internal const string None = "None"; + } + + protected struct RoutingChoiceType + { + internal const string MicrosoftRouting = "MicrosoftRouting"; + internal const string InternalRouting = "InternalRouting"; + } + + protected struct KeyType + { + internal const string Service = "Service"; + internal const string Account = "Account"; + } + + protected struct SkuNameType + { + internal const string StandardLRS = "Standard_LRS"; + internal const string StandardGRS = "Standard_GRS"; + internal const string StandardRagrs = "Standard_RAGRS"; + internal const string StandardZRS = "Standard_ZRS"; + internal const string PremiumLRS = "Premium_LRS"; + internal const string PremiumZRS = "Premium_ZRS"; + internal const string StandardGzrs = "Standard_GZRS"; + internal const string StandardRagzrs = "Standard_RAGZRS"; + } + + protected struct StorageKindType + { + internal const string Storage = "Storage"; + internal const string StorageV2 = "StorageV2"; + internal const string BlobStorage = "BlobStorage"; + internal const string FileStorage = "FileStorage"; + internal const string BlockBlobStorage = "BlockBlobStorage"; + } + + protected struct MinimumTlsVersionType + { + internal const string TLS10 = "TLS1_0"; + internal const string TLS11 = "TLS1_1"; + internal const string TLS12 = "TLS1_2"; } + [Flags] public enum EncryptionSupportServiceEnum { @@ -113,6 +159,19 @@ public IStorageManagementClient StorageClient set { storageClientWrapper = new StorageManagementClientWrapper(value); } } + private Track2StorageManagementClient _track2StorageManagementClient; + public Track2StorageManagementClient StorageClientTrack2 + { + get + { + return _track2StorageManagementClient ?? (_track2StorageManagementClient = new Track2StorageManagementClient( + Microsoft.Azure.Commands.Common.Authentication.AzureSession.Instance.ClientFactory, + DefaultContext)); + } + + set { _track2StorageManagementClient = value; } + } + public string SubscriptionId { get @@ -121,42 +180,40 @@ public string SubscriptionId } } - protected static AccessTier ParseAccessTier(string accessTier) + + protected static Track2Models.AccessTier ParseAccessTier(string accessTier) { - AccessTier returnAccessTier; - if (!Enum.TryParse(accessTier, true, out returnAccessTier)) + Track2Models.AccessTier returnAccessTier; + if (!Enum.TryParse(accessTier, true, out returnAccessTier)) { throw new ArgumentOutOfRangeException("AccessTier"); } return returnAccessTier; } - protected static Encryption ParseEncryption(bool storageEncryption = false, bool keyVaultEncryption = false, string keyName = null, string keyVersion = null, string keyVaultUri = null) + protected static Track2Models.Encryption ParseEncryption(bool storageEncryption = false, bool keyVaultEncryption = false, string keyName = null, string keyVersion = null, string keyVaultUri = null) { - Encryption accountEncryption = new Encryption(); + Track2Models.Encryption accountEncryption = + new Track2Models.Encryption(Track2Models.KeySource.MicrosoftKeyvault); if (storageEncryption) { - accountEncryption.KeySource = "Microsoft.Storage"; + accountEncryption.KeySource = Track2Models.KeySource.MicrosoftStorage; } if (keyVaultEncryption) { - accountEncryption.KeySource = "Microsoft.Keyvault"; - accountEncryption.KeyVaultProperties = new KeyVaultProperties(keyName, keyVersion, keyVaultUri); + accountEncryption.KeySource = Track2Models.KeySource.MicrosoftKeyvault; + accountEncryption.KeyVaultProperties = new Track2Models.KeyVaultProperties(); + accountEncryption.KeyVaultProperties.KeyName = keyName; + accountEncryption.KeyVaultProperties.KeyVersion = keyVersion; + accountEncryption.KeyVaultProperties.KeyVaultUri = new Uri(keyVaultUri); } return accountEncryption; } - protected void WriteStorageAccount(StorageModels.StorageAccount storageAccount) - { - WriteObject(PSStorageAccount.Create(storageAccount, this.StorageClient)); - } - - protected void WriteStorageAccountList(IEnumerable storageAccounts) + protected void WriteStorageAccount(Track2.StorageAccountResource storageAccountResource) { - List output = new List(); - storageAccounts.ForEach(storageAccount => output.Add(PSStorageAccount.Create(storageAccount, this.StorageClient))); - WriteObject(output, true); + WriteObject(PSStorageAccount.Create(storageAccountResource, this.StorageClientTrack2)); } public static string GetIdentityTypeString(string inputIdentityType) @@ -167,21 +224,21 @@ public static string GetIdentityTypeString(string inputIdentityType) } // The parameter validate set make sure the value must be systemAssigned or userAssigned or systemAssignedUserAssigned or None - if (inputIdentityType.ToLower() == AccountIdentityType.systemAssigned.ToLower()) + if (inputIdentityType.ToLower() == AccountIdentityType.SystemAssigned.ToLower()) { - return IdentityType.SystemAssigned; + return AccountIdentityType.SystemAssigned; } - if (inputIdentityType.ToLower() == AccountIdentityType.userAssigned.ToLower()) + if (inputIdentityType.ToLower() == AccountIdentityType.UserAssigned.ToLower()) { - return IdentityType.UserAssigned; + return AccountIdentityType.UserAssigned; } - if (inputIdentityType.ToLower() == AccountIdentityType.systemAssignedUserAssigned.ToLower()) + if (inputIdentityType.ToLower() == AccountIdentityType.SystemAssignedUserAssigned.ToLower()) { - return IdentityType.SystemAssignedUserAssigned; + return AccountIdentityType.SystemAssignedUserAssigned; } - if (inputIdentityType.ToLower() == AccountIdentityType.none.ToLower()) + if (inputIdentityType.ToLower() == AccountIdentityType.None.ToLower()) { - return IdentityType.None; + return AccountIdentityType.None; } throw new ArgumentException("The value for AssignIdentityType is not valid, the valid value are: \"None\", \"SystemAssigned\", \"UserAssigned\", or \"SystemAssignedUserAssigned\"", "AssignIdentityType"); } diff --git a/src/Storage/Storage.Management/Track2StorageManagementClient.cs b/src/Storage/Storage.Management/Track2StorageManagementClient.cs new file mode 100644 index 000000000000..18390527fbd7 --- /dev/null +++ b/src/Storage/Storage.Management/Track2StorageManagementClient.cs @@ -0,0 +1,151 @@ +using Azure.ResourceManager; +using Track2 = Azure.ResourceManager.Storage; +using Track2Model = Azure.ResourceManager.Storage.Models; +using Azure.ResourceManager.Resources; + +using Microsoft.Azure.Commands.Common.Authentication; +using Microsoft.Azure.Commands.Common.Authentication.Abstractions; + +using System.Collections.Generic; +using Azure.ResourceManager.Storage; +using Azure; +using Azure.Core; +using Microsoft.Azure.Commands.Management.Storage.Models; +using Azure.ResourceManager.Storage.Models; +using Microsoft.Azure.Storage.Blob.Protocol; +using System.Diagnostics.Contracts; + +namespace Microsoft.Azure.Commands.Management.Storage +{ + public class Track2StorageManagementClient + { + private ArmClient _armClient; + private string _subscription; + private IClientFactory _clientFactory; + + public Track2StorageManagementClient(IClientFactory clientFactory, IAzureContext context) + { + _clientFactory = clientFactory; + _armClient = _clientFactory.CreateArmClient(context, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId); + _subscription = context.Subscription.Id; + } + + /// + /// Get resource group instance + /// + /// + public ResourceGroupResource GetResourceGroup(string resourcegroup) => + _armClient.GetResourceGroupResource(new global::Azure.Core.ResourceIdentifier( + string.Format("/subscriptions/{0}/resourceGroups/{1}", _subscription, resourcegroup))); + + + public SubscriptionResource GetSubscription(string subscription) => + _armClient.GetSubscriptionResource(new global::Azure.Core.ResourceIdentifier( + string.Format("/subscriptions/{0}", subscription))); + + /// + /// List accounts from subscription + /// + /// + public Pageable ListStorageAccounts() => + _armClient.GetSubscriptionResource(new global::Azure.Core.ResourceIdentifier( + string.Format("/subscriptions/{0}", _subscription))) + .GetStorageAccounts(); + + /// + /// List accounts from Resource group + /// + public Pageable ListStorageAccounts(string resourcegroup) => + GetResourceGroup(resourcegroup).GetStorageAccounts().GetAll(); + + /// + /// Get single storage account with no data + /// + public Track2.StorageAccountResource GetStorageAccount(string resourcegroup, string storageAccountName) => + _armClient.GetStorageAccountResource(Track2.StorageAccountResource.CreateResourceIdentifier(_subscription, resourcegroup, storageAccountName)); + + /// + /// Get a single Storage account with its data + /// + public Track2.StorageAccountResource GetSingleStorageAccount(string resourceGroup, string storageAccountName, StorageAccountExpand? expand = null) => + GetResourceGroup(resourceGroup).GetStorageAccounts().Get(storageAccountName, expand); + + /// + /// Create a Storage account + /// + public StorageAccountResource CreateStorageAccount(string resourceGroup, string storageAccountName, StorageAccountCreateOrUpdateContent content) => + GetResourceGroup(resourceGroup).GetStorageAccounts().CreateOrUpdate(WaitUntil.Completed, storageAccountName, content).Value; + + /// + /// Update a Storage account + /// + public Track2.StorageAccountResource UpdateStorageAccount(string resourcegroup, string storageAccountName, StorageAccountPatch patch) => + GetStorageAccount(resourcegroup, storageAccountName).Update(patch); + + /// + /// Get BlobServiceResource with subscription, resource group name, and storage account name + /// + public Track2.BlobServiceResource GetBlobServiceResource(string resourceGroupName, string storageAccountName) => + _armClient.GetBlobServiceResource(Track2.BlobServiceResource.CreateResourceIdentifier(_subscription, resourceGroupName, storageAccountName)); + + /// + /// Get BlobContainerResource with subscription, resource group name, and storage account name + /// + public Track2.BlobContainerResource GetBlobContainerResource(string resourceGroupName, string storageAccountName, string containerName) => + _armClient.GetBlobContainerResource(Track2.BlobContainerResource.CreateResourceIdentifier(_subscription, resourceGroupName, storageAccountName, containerName)); + + /// + /// List blob containers under a resource group and storage account + /// + public Track2.BlobContainerCollection GetBlobContainers(string resourceGroupName, string storageAccountName) => + GetBlobServiceResource(resourceGroupName, storageAccountName).GetBlobContainers(); + + /// + /// Get a blob container under a resource group and storage account with container name + /// + public Track2.BlobContainerResource GetBlobContainer(string resourceGroupName, string storageAccountName, string containerName) => + GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).Get(); + + /// + /// Update a blob container + /// + public Track2.BlobContainerResource UpdateBlobContainer(string resourceGroupName, string storageAccountName, string containerName, BlobContainerData data) => + GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).Update(data); + + /// + /// Create a blob container + /// + public Track2.BlobContainerResource CreateBlobContainer(string resourceGroupName, string storageAccountName, string containerName, BlobContainerData data) => + GetBlobContainers(resourceGroupName, storageAccountName).CreateOrUpdate(WaitUntil.Completed, containerName, data).Value; + + /// + /// Get immutability policy of a blob container + /// + public Track2.ImmutabilityPolicyResource GetImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, string etag) => + GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().Get(etag); + + /// + /// Lock immutability policy of a blob container + /// + public Track2.ImmutabilityPolicyResource LockImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, string etag) => + GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().LockImmutabilityPolicy(etag); + + /// + /// Create immutability policy for a blob container + /// + public Track2.ImmutabilityPolicyResource CreateImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, ImmutabilityPolicyData data, string etag) => + GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().CreateOrUpdate(WaitUntil.Completed, data, etag).Value; + + /// + /// Extend immutability policy for a blob container + /// + public Track2.ImmutabilityPolicyResource ExtendImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, ImmutabilityPolicyData data, string etag) => + GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().ExtendImmutabilityPolicy(etag, data); + + /// + /// Delete immutability policy for a blob container + /// + public Track2.ImmutabilityPolicyResource DeleteImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, string etag) => + GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().Delete(WaitUntil.Completed, etag).Value; + } +} \ No newline at end of file From c5fc86e9047f215783a0a6a05c9e62e38c3c344b Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Wed, 18 May 2022 11:40:40 +0800 Subject: [PATCH 02/11] fix bugs and formatting per comments --- .../StorageAccount/GetAzureStorageAccount.cs | 1 - .../StorageAccount/NewAzureStorageAccount.cs | 11 ++--------- .../StorageAccount/SetAzureStorageAccount.cs | 18 +++++++++++------- .../StorageAccount/StorageAccountBaseCmdlet.cs | 4 ++-- 4 files changed, 15 insertions(+), 19 deletions(-) diff --git a/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccount.cs index a7e9a4a5a0ac..4348ba5dc21b 100644 --- a/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccount.cs @@ -20,7 +20,6 @@ using Microsoft.Rest.Azure; using System.Management.Automation; - namespace Microsoft.Azure.Commands.Management.Storage { [Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "StorageAccount"), OutputType(typeof(PSStorageAccount))] diff --git a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs index 3aeb85b729e6..f68532c34f97 100644 --- a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs @@ -247,7 +247,7 @@ public bool EnableAzureActiveDirectoryDomainServicesForFile [Parameter(Mandatory = false, HelpMessage = "Routing Choice defines the kind of network routing opted by the user. Possible values include: 'MicrosoftRouting', 'InternetRouting'")] [ValidateSet( RoutingChoiceType.MicrosoftRouting, - RoutingChoiceType.InternalRouting, + RoutingChoiceType.InternetRouting, IgnoreCase = true)] public string RoutingChoice; @@ -699,7 +699,6 @@ public override void ExecuteCmdlet() createContent.Encryption.Services = new Track2Models.EncryptionServices(); createContent.Encryption.Services.Blob = new Track2Models.EncryptionService(); } - } } if (this.KeyVaultUri != null || this.KeyName != null || this.KeyVersion != null || this.KeyVaultUserAssignedIdentityId != null) @@ -726,7 +725,6 @@ public override void ExecuteCmdlet() Track2Models.KeySource.MicrosoftStorage); } - if (createContent.Encryption.Services == null) { createContent.Encryption.Services = new Track2Models.EncryptionServices @@ -735,7 +733,6 @@ public override void ExecuteCmdlet() }; } - if (this.KeyVaultUri != null || this.KeyName != null || this.KeyVersion != null) { @@ -792,8 +789,7 @@ public override void ExecuteCmdlet() } if (sasExpirationPeriod != null) { - createContent.SasPolicy = new Track2Models.SasPolicy(sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss"), null); - + createContent.SasPolicy = new Track2Models.SasPolicy(sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss"), Track2Models.ExpirationAction.Log); } if (keyExpirationPeriodInDay != null) { @@ -820,7 +816,6 @@ public override void ExecuteCmdlet() Enabled = this.EnableAccountLevelImmutability.IsPresent }; - if (this.immutabilityPeriod != null || this.ImmutabilityPolicyState != null) { createContent.ImmutableStorageWithVersioning.ImmutabilityPolicy = new Track2Models.AccountImmutabilityPolicyProperties @@ -828,10 +823,8 @@ public override void ExecuteCmdlet() ImmutabilityPeriodSinceCreationInDays = this.ImmutabilityPeriod, State = this.ImmutabilityPolicyState, }; - } } - var createAccountResponse = this.StorageClientTrack2.CreateStorageAccount(this.ResourceGroupName, this.Name, createContent); var storageAccount = this.StorageClientTrack2.GetSingleStorageAccount(this.ResourceGroupName, this.Name); diff --git a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs index a68f03e11c51..438e0fad4317 100644 --- a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs @@ -24,6 +24,7 @@ using Microsoft.WindowsAzure.Commands.Utilities.Common; using Azure.Core; + namespace Microsoft.Azure.Commands.Management.Storage { /// @@ -242,7 +243,7 @@ public bool EnableAzureActiveDirectoryDomainServicesForFile [Parameter(Mandatory = false, HelpMessage = "Routing Choice defines the kind of network routing opted by the user. Possible values include: 'MicrosoftRouting', 'InternetRouting'")] [ValidateSet( RoutingChoiceType.MicrosoftRouting, - RoutingChoiceType.InternalRouting, + RoutingChoiceType.InternetRouting, IgnoreCase = true)] [ValidateNotNullOrEmpty] public string RoutingChoice; @@ -574,7 +575,6 @@ public override void ExecuteCmdlet() } } } - } } @@ -753,7 +753,7 @@ public override void ExecuteCmdlet() if (sasExpirationPeriod != null) { storageAccountPatch.SasPolicy = new Track2Models.SasPolicy( - this.sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss"), null); + this.sasExpirationPeriod.Value.ToString(@"d\.hh\:mm\:ss"), Track2Models.ExpirationAction.Log); } if (keyExpirationPeriodInDay != null) { @@ -773,11 +773,15 @@ public override void ExecuteCmdlet() if (this.immutabilityPeriod != null || this.ImmutabilityPolicyState != null) { storageAccountPatch.ImmutableStorageWithVersioning = new Track2Models.ImmutableStorageAccount(); - storageAccountPatch.ImmutableStorageWithVersioning.ImmutabilityPolicy = new Track2Models.AccountImmutabilityPolicyProperties + storageAccountPatch.ImmutableStorageWithVersioning.ImmutabilityPolicy = new Track2Models.AccountImmutabilityPolicyProperties(); + if (this.immutabilityPeriod != null) { - ImmutabilityPeriodSinceCreationInDays = this.immutabilityPeriod, - State = this.ImmutabilityPolicyState, - }; + storageAccountPatch.ImmutableStorageWithVersioning.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays = this.immutabilityPeriod; + } + if (this.ImmutabilityPolicyState != null) + { + storageAccountPatch.ImmutableStorageWithVersioning.ImmutabilityPolicy.State = this.ImmutabilityPolicyState; + } } diff --git a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs index ecb6365fc9f8..3abb05c0c98d 100644 --- a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs +++ b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs @@ -80,14 +80,14 @@ protected struct AccountIdentityType { internal const string SystemAssigned = "SystemAssigned"; internal const string UserAssigned = "UserAssigned"; - internal const string SystemAssignedUserAssigned = "SystemAssignedUserAssigned"; + internal const string SystemAssignedUserAssigned = "SystemAssigned, UserAssigned"; internal const string None = "None"; } protected struct RoutingChoiceType { internal const string MicrosoftRouting = "MicrosoftRouting"; - internal const string InternalRouting = "InternalRouting"; + internal const string InternetRouting = "InternetRouting"; } protected struct KeyType From 1abf7fed750e50e40b2e141e18d6fa52ae8117ba Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Thu, 19 May 2022 12:30:35 +0800 Subject: [PATCH 03/11] Fix AccountIdentityType --- .../StorageAccount/NewAzureStorageAccount.cs | 10 ++++++++-- .../StorageAccount/SetAzureStorageAccount.cs | 11 ++++++++--- .../StorageAccount/StorageAccountBaseCmdlet.cs | 3 ++- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs index f68532c34f97..f87487718520 100644 --- a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccount.cs @@ -591,11 +591,17 @@ public override void ExecuteCmdlet() new ManagedServiceIdentity(ManagedServiceIdentityType.SystemAssigned); if (this.IdentityType != null) { - createContent.Identity.ManagedServiceIdentityType = new ManagedServiceIdentityType(this.IdentityType); + if (this.IdentityType == AccountIdentityType.SystemAssignedUserAssigned) + { + createContent.Identity.ManagedServiceIdentityType = new ManagedServiceIdentityType(AccountIdentityType.SystemAssignedUserAssignedTrack2); + } else + { + createContent.Identity.ManagedServiceIdentityType = new ManagedServiceIdentityType(this.IdentityType); + } } if (this.UserAssignedIdentityId != null) { - if (createContent.Identity.ManagedServiceIdentityType != ManagedServiceIdentityType.UserAssigned && createContent.Identity.ManagedServiceIdentityType != ManagedServiceIdentityType.SystemAssignedUserAssigned) + if (createContent.Identity.ManagedServiceIdentityType != AccountIdentityType.UserAssigned && createContent.Identity.ManagedServiceIdentityType != AccountIdentityType.SystemAssignedUserAssignedTrack2) { throw new ArgumentException("UserAssignIdentityId should only be specified when AssignIdentityType is UserAssigned or SystemAssignedUserAssigned.", "UserAssignIdentityId"); } diff --git a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs index 438e0fad4317..fef32205e11c 100644 --- a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs +++ b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccount.cs @@ -24,7 +24,6 @@ using Microsoft.WindowsAzure.Commands.Utilities.Common; using Azure.Core; - namespace Microsoft.Azure.Commands.Management.Storage { /// @@ -551,11 +550,17 @@ public override void ExecuteCmdlet() storageAccountPatch.Identity = new Track2.ManagedServiceIdentity(Track2.ManagedServiceIdentityType.SystemAssigned); if (this.IdentityType != null) { - storageAccountPatch.Identity.ManagedServiceIdentityType = new Track2.ManagedServiceIdentityType(this.IdentityType); + if (this.IdentityType == AccountIdentityType.SystemAssignedUserAssigned) + { + storageAccountPatch.Identity.ManagedServiceIdentityType = new Track2.ManagedServiceIdentityType(AccountIdentityType.SystemAssignedUserAssignedTrack2); + } else + { + storageAccountPatch.Identity.ManagedServiceIdentityType = new Track2.ManagedServiceIdentityType(this.IdentityType); + } } if (this.UserAssignedIdentityId != null) { - if (storageAccountPatch.Identity.ManagedServiceIdentityType != Track2.ManagedServiceIdentityType.UserAssigned && storageAccountPatch.Identity.ManagedServiceIdentityType != Track2.ManagedServiceIdentityType.SystemAssignedUserAssigned) + if (storageAccountPatch.Identity.ManagedServiceIdentityType != AccountIdentityType.UserAssigned && storageAccountPatch.Identity.ManagedServiceIdentityType != AccountIdentityType.SystemAssignedUserAssignedTrack2) { throw new ArgumentException("UserAssignIdentityId should only be specified when AssignIdentityType is UserAssigned or SystemAssignedUserAssigned.", "UserAssignIdentityId"); } diff --git a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs index 3abb05c0c98d..68c2bbac4aba 100644 --- a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs +++ b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs @@ -80,7 +80,8 @@ protected struct AccountIdentityType { internal const string SystemAssigned = "SystemAssigned"; internal const string UserAssigned = "UserAssigned"; - internal const string SystemAssignedUserAssigned = "SystemAssigned, UserAssigned"; + internal const string SystemAssignedUserAssigned = "SystemAssignedUserAssigned"; + internal const string SystemAssignedUserAssignedTrack2 = "SystemAssigned, UserAssigned"; internal const string None = "None"; } From 412d6c4bde0d2d05d432b4afc35ac238f75c08af Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Mon, 30 May 2022 15:41:38 +0800 Subject: [PATCH 04/11] migration for restore blob range, managementpolicy related cmdlets --- .../Storage.Management/Models/PSDataPolicy.cs | 197 ++++++++++-------- ...ureStorageAccountManagementPolicyAction.cs | 2 - .../GetAzureStorageAccountManagementPolicy.cs | 11 +- ...ureStorageAccountManagementPolicyFilter.cs | 2 - ...AzureStorageAccountManagementPolicyRule.cs | 2 - ...moveAzureStorageAccountManagementPolicy.cs | 8 +- .../RestoreAzStorageBlobRange.cs | 97 ++++++--- .../SetAzureStorageAccountManagementPolicy.cs | 44 ++-- .../StorageAccountBaseCmdlet.cs | 21 ++ .../Track2StorageManagementClient.cs | 69 +++--- 10 files changed, 273 insertions(+), 180 deletions(-) diff --git a/src/Storage/Storage.Management/Models/PSDataPolicy.cs b/src/Storage/Storage.Management/Models/PSDataPolicy.cs index 79df6fec2255..3f1431ebcb74 100644 --- a/src/Storage/Storage.Management/Models/PSDataPolicy.cs +++ b/src/Storage/Storage.Management/Models/PSDataPolicy.cs @@ -12,7 +12,8 @@ // limitations under the License. // ---------------------------------------------------------------------------------- -using Microsoft.Azure.Management.Storage.Models; +using Track2 = global::Azure.ResourceManager.Storage; +using Azure.ResourceManager.Storage.Models; using Microsoft.WindowsAzure.Commands.Common.Attributes; using System; using System.Collections.Generic; @@ -27,16 +28,17 @@ public class PSManagementPolicy public PSManagementPolicy() { } - public PSManagementPolicy(ManagementPolicy policy, string ResourceGroupName, string StorageAccountName) + public PSManagementPolicy(Track2.ManagementPolicyResource policyResource, string resourceGroupName, string storageAccountName) { - this.ResourceGroupName = ResourceGroupName; - this.StorageAccountName = StorageAccountName; - this.Id = policy.Id; - this.Name = policy.Name; - this.Type = policy.Type; - this.LastModifiedTime = policy.LastModifiedTime; - this.Rules = PSManagementPolicyRule.GetPSManagementPolicyRules(policy.Policy.Rules); + this.ResourceGroupName = resourceGroupName; + this.StorageAccountName = storageAccountName; + this.Id = policyResource.Id; + this.Name = policyResource.Data.Name; + this.Type = Track2.ManagementPolicyResource.ResourceType.ToString(); + this.LastModifiedTime = policyResource.Data.LastModifiedOn; + this.Rules = PSManagementPolicyRule.GetPSManagementPolicyRules(policyResource.Data.Rules); } + [Ps1Xml(Label = "ResourceGroupName", Target = ViewControl.List, Position = 0)] public string ResourceGroupName { get; set; } [Ps1Xml(Label = "StorageAccountName", Target = ViewControl.List, Position = 1)] @@ -47,7 +49,7 @@ public PSManagementPolicy(ManagementPolicy policy, string ResourceGroupName, str [Ps1Xml(Label = "Type", Target = ViewControl.List, Position = 3)] public string Type { get; set; } [Ps1Xml(Label = "LastModifiedTime", Target = ViewControl.List, Position = 4)] - public DateTime? LastModifiedTime { get; set; } + public DateTimeOffset? LastModifiedTime { get; set; } [Ps1Xml(Label = "Rules", Target = ViewControl.List, ScriptBlock = "ConvertTo-Json $_ -Depth 10", Position = 5)] public PSManagementPolicyRule[] Rules { get; set; } } @@ -65,43 +67,45 @@ public PSManagementPolicyRule() { } - public PSManagementPolicyRule(ManagementPolicyRule rule) + public PSManagementPolicyRule(global::Azure.ResourceManager.Storage.Models.ManagementPolicyRule rule) { this.Enabled = rule.Enabled; this.Name = rule.Name; this.Definition = rule.Definition is null ? null : new PSManagementPolicyDefinition(rule.Definition); } - public ManagementPolicyRule ParseManagementPolicyRule() + public Track2.Models.ManagementPolicyRule ParseManagementPolicyRule() { - ManagementPolicyRule rule = new ManagementPolicyRule(); + Track2.Models.ManagementPolicyRule rule = new Track2.Models.ManagementPolicyRule( + this.Name, + RuleType.Lifecycle, + this.Definition is null ? null : this.Definition.ParseManagementPolicyDefination() + ); rule.Enabled = this.Enabled; - rule.Name = this.Name; - rule.Definition = this.Definition is null ? null : this.Definition.ParseManagementPolicyDefination(); return rule; } - public static PSManagementPolicyRule[] GetPSManagementPolicyRules(IList rules) + public static PSManagementPolicyRule[] GetPSManagementPolicyRules(IList rules) { if (rules == null) { return null; } List psrules = new List(); - foreach (ManagementPolicyRule rule in rules) + foreach (Track2.Models.ManagementPolicyRule rule in rules) { psrules.Add(new PSManagementPolicyRule(rule)); } return psrules.ToArray(); } - public static List ParseManagementPolicyRules(PSManagementPolicyRule[] psrules) + public static List ParseManagementPolicyRules(PSManagementPolicyRule[] psrules) { if (psrules == null) { return null; } - List rules = new List(); + List rules = new List(); foreach (PSManagementPolicyRule psrule in psrules) { rules.Add(psrule.ParseManagementPolicyRule()); @@ -122,18 +126,18 @@ public PSManagementPolicyDefinition() { } - public PSManagementPolicyDefinition(ManagementPolicyDefinition defination) + public PSManagementPolicyDefinition(Track2.Models.ManagementPolicyDefinition defination) { this.Actions = defination.Actions is null ? null : new PSManagementPolicyActionGroup(defination.Actions); this.Filters = defination.Filters is null ? null : new PSManagementPolicyRuleFilter(defination.Filters); } - public ManagementPolicyDefinition ParseManagementPolicyDefination() + public Track2.Models.ManagementPolicyDefinition ParseManagementPolicyDefination() { - return new ManagementPolicyDefinition() - { - Actions = this.Actions is null ? null : this.Actions.ParseManagementPolicyAction(), - Filters = this.Filters is null ? null : this.Filters.ParseManagementPolicyFilter() - }; + Track2.Models.ManagementPolicyAction actions = this.Actions is null ? null : this.Actions.ParseManagementPolicyAction(); + Track2.Models.ManagementPolicyDefinition policyDefinition = new Track2.Models.ManagementPolicyDefinition(actions); + policyDefinition.Filters = this.Filters is null ? null : this.Filters.ParseManagementPolicyFilter(); + + return policyDefinition; } public static string[] StringListToArray(IList list) @@ -153,23 +157,38 @@ public class PSManagementPolicyRuleFilter public PSManagementPolicyRuleFilter() { } - public PSManagementPolicyRuleFilter(ManagementPolicyFilter filter) + public PSManagementPolicyRuleFilter(Track2.Models.ManagementPolicyFilter filter) { this.PrefixMatch = StringListToArray(filter.PrefixMatch); this.BlobTypes = StringListToArray(filter.BlobTypes); } - public ManagementPolicyFilter ParseManagementPolicyFilter() + public Track2.Models.ManagementPolicyFilter ParseManagementPolicyFilter() { - return new ManagementPolicyFilter() + Track2.Models.ManagementPolicyFilter policyFilter = new Track2.Models.ManagementPolicyFilter(StringArrayToList(this.BlobTypes)); + if (this.PrefixMatch != null) { - PrefixMatch = StringArrayToList(this.PrefixMatch), - BlobTypes = StringArrayToList(this.BlobTypes), - }; + foreach (string prefixMatch in this.PrefixMatch) + { + policyFilter.PrefixMatch.Add(prefixMatch); + } + } + return policyFilter; } public static string[] StringListToArray(IList list) { - return (list is null ? null : ((List)list).ToArray()); + if (list is null) + { + return null; + } + + var result = new string[list.Count]; + + for (int i = 0; i < list.Count; i++) + { + result[i] = list[i].ToString(); + } + return result; } public static List StringArrayToList(string[] array) @@ -190,15 +209,15 @@ public class PSManagementPolicyActionGroup public PSManagementPolicyActionGroup() { } - public PSManagementPolicyActionGroup(ManagementPolicyAction action) + public PSManagementPolicyActionGroup(Track2.Models.ManagementPolicyAction action) { this.BaseBlob = (action is null || action.BaseBlob is null) ? null : new PSManagementPolicyBaseBlob(action.BaseBlob); this.Snapshot = (action is null || action.Snapshot is null) ? null : new PSManagementPolicySnapShot(action.Snapshot); this.Version = (action is null || action.Version is null) ? null : new PSManagementPolicyVersion(action.Version); } - public ManagementPolicyAction ParseManagementPolicyAction() + public Track2.Models.ManagementPolicyAction ParseManagementPolicyAction() { - return new ManagementPolicyAction() + return new Track2.Models.ManagementPolicyAction() { BaseBlob = this.BaseBlob is null ? null : this.BaseBlob.ParseManagementPolicyBaseBlob(), Snapshot = this.Snapshot is null ? null : this.Snapshot.ParseManagementPolicySnapShot(), @@ -220,16 +239,16 @@ public class PSManagementPolicyBaseBlob public PSManagementPolicyBaseBlob() { } - public PSManagementPolicyBaseBlob(ManagementPolicyBaseBlob blobAction) + public PSManagementPolicyBaseBlob(Track2.Models.ManagementPolicyBaseBlob blobAction) { this.TierToCool = blobAction.TierToCool is null ? null : new PSDateAfterModification(blobAction.TierToCool); this.TierToArchive = blobAction.TierToArchive is null ? null : new PSDateAfterModification(blobAction.TierToArchive); this.Delete = blobAction.Delete is null ? null : new PSDateAfterModification(blobAction.Delete); this.EnableAutoTierToHotFromCool = blobAction.EnableAutoTierToHotFromCool; } - public ManagementPolicyBaseBlob ParseManagementPolicyBaseBlob() + public Track2.Models.ManagementPolicyBaseBlob ParseManagementPolicyBaseBlob() { - return new ManagementPolicyBaseBlob() + return new Track2.Models.ManagementPolicyBaseBlob() { TierToCool = this.TierToCool is null ? null : this.TierToCool.ParseDateAfterModification(), TierToArchive = this.TierToArchive is null ? null : this.TierToArchive.ParseDateAfterModification(), @@ -251,20 +270,32 @@ public class PSManagementPolicySnapShot public PSManagementPolicySnapShot() { } - public PSManagementPolicySnapShot(ManagementPolicySnapShot blobAction) + public PSManagementPolicySnapShot(Track2.Models.ManagementPolicySnapShot blobAction) { - this.Delete = blobAction.Delete is null ? null : new PSDateAfterCreation(blobAction.Delete); - this.TierToCool = blobAction.TierToCool is null ? null : new PSDateAfterCreation(blobAction.TierToCool); - this.TierToArchive = blobAction.TierToArchive is null ? null : new PSDateAfterCreation(blobAction.TierToArchive); + + this.Delete = blobAction.DeleteDaysAfterCreationGreaterThan is null ? null : new PSDateAfterCreation((int)blobAction.DeleteDaysAfterCreationGreaterThan); + this.TierToCool = blobAction.TierToCoolDaysAfterCreationGreaterThan is null ? null : new PSDateAfterCreation((int)blobAction.TierToCoolDaysAfterCreationGreaterThan); + TierToArchive = blobAction.TierToArchiveDaysAfterCreationGreaterThan is null ? null : new PSDateAfterCreation((int)blobAction.TierToArchiveDaysAfterCreationGreaterThan); } - public ManagementPolicySnapShot ParseManagementPolicySnapShot() + public Track2.Models.ManagementPolicySnapShot ParseManagementPolicySnapShot() { - return new ManagementPolicySnapShot() + + Track2.Models.ManagementPolicySnapShot snapShot = new Track2.Models.ManagementPolicySnapShot(); + + if (this.Delete != null) { - Delete = this.Delete is null ? null : this.Delete.ParseDateAfterCreation(), - TierToCool = this.TierToCool is null ? null : this.TierToCool.ParseDateAfterCreation(), - TierToArchive = this.TierToArchive is null ? null : this.TierToArchive.ParseDateAfterCreation() - }; + snapShot.DeleteDaysAfterCreationGreaterThan = this.Delete.DaysAfterCreationGreaterThan; + } + if (this.TierToCool != null) + { + snapShot.TierToCoolDaysAfterCreationGreaterThan = this.TierToCool.DaysAfterCreationGreaterThan; + } + if (this.TierToArchive != null) + { + snapShot.TierToArchiveDaysAfterCreationGreaterThan = this.TierToArchive.DaysAfterCreationGreaterThan; + } + + return snapShot; } } @@ -280,20 +311,29 @@ public class PSManagementPolicyVersion public PSManagementPolicyVersion() { } - public PSManagementPolicyVersion(ManagementPolicyVersion blobAction) + public PSManagementPolicyVersion(Track2.Models.ManagementPolicyVersion blobAction) { - this.Delete = blobAction.Delete is null ? null : new PSDateAfterCreation(blobAction.Delete); - this.TierToCool = blobAction.TierToCool is null ? null : new PSDateAfterCreation(blobAction.TierToCool); - this.TierToArchive = blobAction.TierToArchive is null ? null : new PSDateAfterCreation(blobAction.TierToArchive); + this.Delete = blobAction.DeleteDaysAfterCreationGreaterThan is null ? null : new PSDateAfterCreation((int)blobAction.DeleteDaysAfterCreationGreaterThan); + this.TierToCool = blobAction.TierToCoolDaysAfterCreationGreaterThan is null ? null :new PSDateAfterCreation((int)blobAction.TierToCoolDaysAfterCreationGreaterThan); + this.TierToArchive = blobAction.TierToArchiveDaysAfterCreationGreaterThan is null ? null : new PSDateAfterCreation((int)blobAction.TierToArchiveDaysAfterCreationGreaterThan); } - public ManagementPolicyVersion ParseManagementPolicyVersion() + public Track2.Models.ManagementPolicyVersion ParseManagementPolicyVersion() { - return new ManagementPolicyVersion() + Track2.Models.ManagementPolicyVersion policyVersion = new Track2.Models.ManagementPolicyVersion(); + if (this.Delete != null) { - Delete = this.Delete is null ? null : this.Delete.ParseDateAfterCreation(), - TierToCool = this.TierToCool is null ? null : this.TierToCool.ParseDateAfterCreation(), - TierToArchive = this.TierToArchive is null ? null : this.TierToArchive.ParseDateAfterCreation() - }; + policyVersion.DeleteDaysAfterCreationGreaterThan = this.Delete.DaysAfterCreationGreaterThan; + } + if (this.TierToCool != null) + { + policyVersion.TierToCoolDaysAfterCreationGreaterThan = this.TierToCool.DaysAfterCreationGreaterThan; + } + if (this.TierToArchive != null) + { + policyVersion.TierToArchiveDaysAfterCreationGreaterThan = this.TierToArchive.DaysAfterCreationGreaterThan; + } + + return policyVersion; } } @@ -304,6 +344,7 @@ public class PSDateAfterModification { public int? DaysAfterModificationGreaterThan { get; set; } public int? DaysAfterLastAccessTimeGreaterThan { get; set; } + public int? DaysAfterLastTierChangeGreaterThan { get; set; } public PSDateAfterModification() @@ -331,7 +372,7 @@ public PSDateAfterModification(int? daysAfterModificationGreaterThan, int? daysA this.DaysAfterLastTierChangeGreaterThan = DaysAfterLastTierChangeGreaterThan; } - public PSDateAfterModification(DateAfterModification data) + public PSDateAfterModification(Track2.Models.DateAfterModification data) { if (data.DaysAfterModificationGreaterThan is null) { @@ -349,18 +390,15 @@ public PSDateAfterModification(DateAfterModification data) { this.DaysAfterLastAccessTimeGreaterThan = Convert.ToInt32(data.DaysAfterLastAccessTimeGreaterThan); } - if (data.DaysAfterLastTierChangeGreaterThan is null) - { - this.DaysAfterLastTierChangeGreaterThan = null; - } - else - { - this.DaysAfterLastTierChangeGreaterThan = Convert.ToInt32(data.DaysAfterLastTierChangeGreaterThan); - } } - public DateAfterModification ParseDateAfterModification() + public Track2.Models.DateAfterModification ParseDateAfterModification() { - return new DateAfterModification(this.DaysAfterModificationGreaterThan, this.DaysAfterLastAccessTimeGreaterThan, this.DaysAfterLastTierChangeGreaterThan); + Track2.Models.DateAfterModification dateAfterModification = new Track2.Models.DateAfterModification(); + dateAfterModification.DaysAfterLastAccessTimeGreaterThan = this.DaysAfterLastAccessTimeGreaterThan; + dateAfterModification.DaysAfterModificationGreaterThan = this.DaysAfterModificationGreaterThan; + + return dateAfterModification; + } } @@ -382,29 +420,10 @@ public PSDateAfterCreation(int daysAfterCreationGreaterThan) { this.DaysAfterCreationGreaterThan = daysAfterCreationGreaterThan; } - public PSDateAfterCreation(int daysAfterCreationGreaterThan, int? DaysAfterLastTierChangeGreaterThan) { this.DaysAfterCreationGreaterThan = daysAfterCreationGreaterThan; this.DaysAfterLastTierChangeGreaterThan = DaysAfterLastTierChangeGreaterThan; } - - public PSDateAfterCreation(DateAfterCreation data) - { - this.DaysAfterCreationGreaterThan = Convert.ToInt32(data.DaysAfterCreationGreaterThan); - if (data.DaysAfterLastTierChangeGreaterThan is null) - { - this.DaysAfterLastTierChangeGreaterThan = null; - } - else - { - this.DaysAfterLastTierChangeGreaterThan = Convert.ToInt32(data.DaysAfterLastTierChangeGreaterThan); - } - } - public DateAfterCreation ParseDateAfterCreation() - { - return new DateAfterCreation(this.DaysAfterCreationGreaterThan, this.DaysAfterLastTierChangeGreaterThan); - } } - } diff --git a/src/Storage/Storage.Management/StorageAccount/AddAzureStorageAccountManagementPolicyAction.cs b/src/Storage/Storage.Management/StorageAccount/AddAzureStorageAccountManagementPolicyAction.cs index 7a705a7de168..0ffd7acb1e11 100644 --- a/src/Storage/Storage.Management/StorageAccount/AddAzureStorageAccountManagementPolicyAction.cs +++ b/src/Storage/Storage.Management/StorageAccount/AddAzureStorageAccountManagementPolicyAction.cs @@ -14,8 +14,6 @@ using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; using System.Globalization; using System.Management.Automation; diff --git a/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccountManagementPolicy.cs b/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccountManagementPolicy.cs index 3a733089ac2d..5cef34258a16 100644 --- a/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccountManagementPolicy.cs +++ b/src/Storage/Storage.Management/StorageAccount/GetAzureStorageAccountManagementPolicy.cs @@ -12,11 +12,10 @@ // limitations under the License. // ---------------------------------------------------------------------------------- +using Azure.ResourceManager.Storage; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; using System.Management.Automation; @@ -95,11 +94,11 @@ public override void ExecuteCmdlet() break; } - ManagementPolicy managementPolicy = this.StorageClient.ManagementPolicies.Get( - this.ResourceGroupName, - this.StorageAccountName); + ManagementPolicyResource policy = this.StorageClientTrack2.GetManagementPolicyResource( + this.ResourceGroupName, this.StorageAccountName, "default").Get(); - WriteObject(new PSManagementPolicy(managementPolicy, this.ResourceGroupName, this.StorageAccountName), true); + var result = new PSManagementPolicy(policy, this.ResourceGroupName, this.StorageAccountName); + WriteObject(result, true); } } } diff --git a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccountManagementPolicyFilter.cs b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccountManagementPolicyFilter.cs index ebc60cc76948..1f86cde882c7 100644 --- a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccountManagementPolicyFilter.cs +++ b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccountManagementPolicyFilter.cs @@ -14,8 +14,6 @@ using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; using System.Management.Automation; namespace Microsoft.Azure.Commands.Management.Storage diff --git a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccountManagementPolicyRule.cs b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccountManagementPolicyRule.cs index 1ec8df9d86a9..5814084564d8 100644 --- a/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccountManagementPolicyRule.cs +++ b/src/Storage/Storage.Management/StorageAccount/NewAzureStorageAccountManagementPolicyRule.cs @@ -14,8 +14,6 @@ using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; using System.Management.Automation; diff --git a/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccountManagementPolicy.cs b/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccountManagementPolicy.cs index 3ca9d1f78763..8481b536d316 100644 --- a/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccountManagementPolicy.cs +++ b/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccountManagementPolicy.cs @@ -15,9 +15,8 @@ using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; using System.Management.Automation; +using Azure; namespace Microsoft.Azure.Commands.Management.Storage { @@ -116,9 +115,8 @@ public override void ExecuteCmdlet() break; } - this.StorageClient.ManagementPolicies.Delete( - this.ResourceGroupName, - this.StorageAccountName); + this.StorageClientTrack2.GetManagementPolicyResource(this.ResourceGroupName, this.StorageAccountName, "default") + .Delete(WaitUntil.Completed); if (PassThru.IsPresent) { diff --git a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs index b8e3a9473b2c..317de42e34c2 100644 --- a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs +++ b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs @@ -12,15 +12,17 @@ // limitations under the License. // ---------------------------------------------------------------------------------- +using Track2 = Azure.ResourceManager.Storage; +using Track2Models = Azure.ResourceManager.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; using Microsoft.Rest.Azure; using System; +using System.Collections.Generic; using System.Management.Automation; using System.Threading.Tasks; +using Azure; namespace Microsoft.Azure.Commands.Management.Storage { @@ -79,7 +81,7 @@ public class RestoreAzureStorageBlobRangeCommand : StorageAccountBaseCmdlet [Parameter(Mandatory = true, HelpMessage = "The Time to Restore Blob.")] [ValidateNotNull] - public DateTime TimeToRestore { get; set; } + public DateTimeOffset TimeToRestore { get; set; } [Parameter(Mandatory = false, HelpMessage = "The blob range to Restore.")] [ValidateNotNull] @@ -119,49 +121,80 @@ public override void ExecuteCmdlet() if (ShouldProcess(this.StorageAccountName, "Restore Blob Range")) { if (waitForComplete) - { - Task> beginTask = this.StorageClient.StorageAccounts.BeginRestoreBlobRangesWithHttpMessagesAsync( - this.ResourceGroupName, - this.StorageAccountName, - this.TimeToRestore, - PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange)); - - beginTask.Wait(); - - AzureOperationResponse response = beginTask.Result; - - WriteWarning(string.Format("Restore blob ranges with Id '{0}' started. Restore blob ranges time to complete is dependent on the size of the restore.", response.Body is null ? "" : response.Body.RestoreId)); + { + Track2.StorageAccountResource account = this.StorageClientTrack2.GetStorageAccount(this.ResourceGroupName, this.StorageAccountName); + var restoreLro = account.RestoreBlobRanges( + WaitUntil.Started, + new Track2Models.BlobRestoreContent( + this.TimeToRestore, + ParseBlobRestoreRanges(this.BlobRestoreRange)) + ); + + Dictionary temp = (Dictionary)restoreLro.GetRawResponse().Content.ToObjectFromJson(); + object restoreId; + + if (temp.TryGetValue("restoreId", out restoreId)) + { + WriteWarning(string.Format("Restore blob ranges with Id '{0}' started. Restore blob ranges time to complete is dependent on the size of the restore.", restoreId)); + } + else + { + WriteWarning(string.Format("Restore blob ranges with Id started. Restore blob ranges time to complete is dependent on the size of the restore.")); + } - Task> waitTask = ((StorageManagementClient)this.StorageClient).GetPostOrDeleteOperationResultAsync(response, null, new System.Threading.CancellationToken()); try { - waitTask.Wait(); + var result = restoreLro.WaitForCompletion().Value; + WriteObject(new PSBlobRestoreStatus(result)); } - catch (System.AggregateException ex) when (ex.InnerException is CloudException) + catch (Exception ex) { - throw new InvalidJobStateException(string.Format("Blob ranges restore failed with information: '{0}'.", ((CloudException)ex.InnerException).Response.Content)); + throw new InvalidJobStateException(string.Format("Blob ranges restore failed with information: '{0}'.", ex.ToString())); } - - AzureOperationResponse result = waitTask.Result; - - WriteObject(new PSBlobRestoreStatus(result.Body)); - } else { - BlobRestoreStatus status = this.StorageClient.StorageAccounts.BeginRestoreBlobRanges( - this.ResourceGroupName, - this.StorageAccountName, - this.TimeToRestore, - PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange)); - - WriteObject(new PSBlobRestoreStatus(status)); - if (status != null && status.Status == BlobRestoreProgressStatus.Failed) + Track2.StorageAccountResource account = this.StorageClientTrack2.GetStorageAccount(this.ResourceGroupName, this.StorageAccountName); + var restoreLro = account.RestoreBlobRanges( + WaitUntil.Completed, + new Track2Models.BlobRestoreContent( + this.TimeToRestore.ToUniversalTime(), + ParseBlobRestoreRanges(this.BlobRestoreRange))); + if (restoreLro.Value != null && restoreLro.Value.Status != null && restoreLro.Value.Status == Track2Models.BlobRestoreProgressStatus.Failed) { throw new InvalidJobStateException("Blob ranges restore failed."); } + WriteObject(new PSBlobRestoreStatus(restoreLro.Value)); + } + } + } + + /// + /// Parse from PSBlobRestoreRange list to BlobRestoreRange list + /// + public static IList ParseBlobRestoreRanges(PSBlobRestoreRange[] ranges) + { + IList re = new List(); + if (ranges == null) + { + re.Add( + new Track2Models.BlobRestoreRange( + startRange: "", + endRange: "" + )); + } + else + { + foreach (PSBlobRestoreRange range in ranges) + { + re.Add( + new Track2Models.BlobRestoreRange( + startRange: range.StartRange, + endRange: range.EndRange + )); } } + return re; } } } diff --git a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccountManagementPolicy.cs b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccountManagementPolicy.cs index 28ef1b36de10..1c3527158d68 100644 --- a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccountManagementPolicy.cs +++ b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccountManagementPolicy.cs @@ -14,14 +14,14 @@ using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; -using Microsoft.Azure.Management.Storage; -using Microsoft.Azure.Management.Storage.Models; using System.Management.Automation; using Newtonsoft.Json.Linq; using System.Globalization; using System.Collections.Generic; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; +using Track2 = Azure.ResourceManager.Storage; +using Azure.ResourceManager.Storage; namespace Microsoft.Azure.Commands.Management.Storage { @@ -62,7 +62,7 @@ public class SetAzureStorageAccountManagementPolicyCommand : StorageAccountBaseC Position = 0, Mandatory = true, HelpMessage = "Resource Group Name.", - ParameterSetName = AccountNamePolicyRuleParameterSet)] + ParameterSetName = AccountNamePolicyRuleParameterSet)] [Parameter( Position = 0, Mandatory = true, @@ -155,7 +155,7 @@ public override void ExecuteCmdlet() base.ExecuteCmdlet(); if (ShouldProcess(this.StorageAccountName, "Set Storage Account Management Policy")) { - if ((this.ParameterSetName == AccountObjectPolicyRuleParameterSet) + if ((this.ParameterSetName == AccountObjectPolicyRuleParameterSet) || (this.ParameterSetName == AccountObjectPolicyObjectParameterSet)) { this.ResourceGroupName = StorageAccount.ResourceGroupName; @@ -168,35 +168,43 @@ public override void ExecuteCmdlet() this.ResourceGroupName = accountResource.ResourceGroupName; this.StorageAccountName = accountResource.ResourceName; } - ManagementPolicy managementPolicy; + + ManagementPolicyResource managementPolicyResource; + Track2.ManagementPolicyData data; switch (this.ParameterSetName) { case AccountObjectPolicyRuleParameterSet: case AccountNamePolicyRuleParameterSet: case AccountResourceIdPolicyRuleParameterSet: - managementPolicy = this.StorageClient.ManagementPolicies.CreateOrUpdate( - this.ResourceGroupName, - this.StorageAccountName, - new ManagementPolicySchema( - //this.version, - PSManagementPolicyRule.ParseManagementPolicyRules(this.Rule))); + + data = new Track2.ManagementPolicyData + { + Rules = PSManagementPolicyRule.ParseManagementPolicyRules(this.Rule) + }; + + managementPolicyResource = this.StorageClientTrack2 + .GetManagementPolicyResource(this.ResourceGroupName, this.StorageAccountName, "default") + .CreateOrUpdate(global::Azure.WaitUntil.Completed, data).Value; break; case AccountObjectPolicyObjectParameterSet: case AccountNamePolicyObjectParameterSet: case AccountResourceIdPolicyObjectParameterSet: - managementPolicy = this.StorageClient.ManagementPolicies.CreateOrUpdate( - this.ResourceGroupName, - this.StorageAccountName, - new ManagementPolicySchema( - //this.Policy.Version, - PSManagementPolicyRule.ParseManagementPolicyRules(this.Policy.Rules))); + + data = new Track2.ManagementPolicyData() + { + Rules = PSManagementPolicyRule.ParseManagementPolicyRules(this.Policy.Rules) + }; + + managementPolicyResource = this.StorageClientTrack2 + .GetManagementPolicyResource(this.ResourceGroupName, this.StorageAccountName, "default") + .CreateOrUpdate(global::Azure.WaitUntil.Completed, data).Value; break; default: throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid ParameterSet: {0}", this.ParameterSetName)); } - WriteObject(new PSManagementPolicy(managementPolicy, this.ResourceGroupName, this.StorageAccountName), true); + WriteObject(new PSManagementPolicy(managementPolicyResource, this.ResourceGroupName, this.StorageAccountName), true); } } } diff --git a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs index 68c2bbac4aba..9a50e7200c66 100644 --- a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs +++ b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs @@ -25,6 +25,8 @@ using System; using System.Collections.Generic; using StorageModels = Microsoft.Azure.Management.Storage.Models; +using Microsoft.Azure.Storage; +using Microsoft.Azure.Storage.Auth; namespace Microsoft.Azure.Commands.Management.Storage { @@ -194,6 +196,7 @@ protected static Track2Models.AccessTier ParseAccessTier(string accessTier) protected static Track2Models.Encryption ParseEncryption(bool storageEncryption = false, bool keyVaultEncryption = false, string keyName = null, string keyVersion = null, string keyVaultUri = null) { + // TODO: Fix the KeySource value. It should be null or empty. Input KeyVault for a placeholder. Track2Models.Encryption accountEncryption = new Track2Models.Encryption(Track2Models.KeySource.MicrosoftKeyvault); @@ -212,6 +215,24 @@ protected static Track2Models.Encryption ParseEncryption(bool storageEncryption return accountEncryption; } + public static CloudStorageAccount GetCloudStorageAccount(Track2.StorageAccountResource storageAccountResource) + { + Uri blobEndpoint = storageAccountResource.Data.PrimaryEndpoints.Blob != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.Blob) : null; + Uri queueEndpoint = storageAccountResource.Data.PrimaryEndpoints.Queue != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.Queue) : null; + Uri tableEndpoint = storageAccountResource.Data.PrimaryEndpoints.Table != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.Table) : null; + Uri fileEndpoint = storageAccountResource.Data.PrimaryEndpoints.File != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.File) : null; + string key = storageAccountResource.GetKeys().Value.Keys[0].Value; + StorageCredentials storageCredentials = new Azure.Storage.Auth.StorageCredentials(storageAccountResource.Data.Name, key); + CloudStorageAccount cloudStorageAccount = new CloudStorageAccount( + storageCredentials, + new StorageUri(blobEndpoint), + new StorageUri(queueEndpoint), + new StorageUri(tableEndpoint), + new StorageUri(fileEndpoint)); + + return cloudStorageAccount; + } + protected void WriteStorageAccount(Track2.StorageAccountResource storageAccountResource) { WriteObject(PSStorageAccount.Create(storageAccountResource, this.StorageClientTrack2)); diff --git a/src/Storage/Storage.Management/Track2StorageManagementClient.cs b/src/Storage/Storage.Management/Track2StorageManagementClient.cs index 18390527fbd7..a603dfa2e62a 100644 --- a/src/Storage/Storage.Management/Track2StorageManagementClient.cs +++ b/src/Storage/Storage.Management/Track2StorageManagementClient.cs @@ -52,6 +52,18 @@ public Pageable ListStorageAccounts() => string.Format("/subscriptions/{0}", _subscription))) .GetStorageAccounts(); + /// + /// Check if a storage account name is available + /// + public CheckNameAvailabilityResult CheckNameAvailability(StorageAccountCheckNameAvailabilityContent content) => + GetSubscription(_subscription).CheckStorageAccountNameAvailability(content); + + /// + /// get Storage usages + /// + public Pageable GetStorageUsages(string location) => + GetSubscription(_subscription).GetUsagesByLocation(location); + /// /// List accounts from Resource group /// @@ -82,6 +94,23 @@ public StorageAccountResource CreateStorageAccount(string resourceGroup, string public Track2.StorageAccountResource UpdateStorageAccount(string resourcegroup, string storageAccountName, StorageAccountPatch patch) => GetStorageAccount(resourcegroup, storageAccountName).Update(patch); + /// + /// Get Blob inventory policy resource + public Track2.BlobInventoryPolicyResource GetBlobInventoryPolicyResource(string resourceGroupName, string storageAccountName, string policyName) => + _armClient.GetBlobInventoryPolicyResource(Track2.BlobInventoryPolicyResource.CreateResourceIdentifier(_subscription, resourceGroupName, storageAccountName, policyName)); + + /// + /// Get immutability policy resource + /// + public Track2.ImmutabilityPolicyResource GetImmutabilityPolicyResource(string resourceGroupName, string storageAccountName, string containerName) => + _armClient.GetImmutabilityPolicyResource(Track2.ImmutabilityPolicyResource.CreateResourceIdentifier(_subscription, resourceGroupName, storageAccountName, containerName)); + + /// + /// Get management policy resource + /// + public Track2.ManagementPolicyResource GetManagementPolicyResource(string resourceGroupName, string storageAccountName, string policyName) => + _armClient.GetManagementPolicyResource(Track2.ManagementPolicyResource.CreateResourceIdentifier(_subscription, resourceGroupName, storageAccountName, policyName)); + /// /// Get BlobServiceResource with subscription, resource group name, and storage account name /// @@ -100,12 +129,6 @@ public Track2.BlobContainerResource GetBlobContainerResource(string resourceGrou public Track2.BlobContainerCollection GetBlobContainers(string resourceGroupName, string storageAccountName) => GetBlobServiceResource(resourceGroupName, storageAccountName).GetBlobContainers(); - /// - /// Get a blob container under a resource group and storage account with container name - /// - public Track2.BlobContainerResource GetBlobContainer(string resourceGroupName, string storageAccountName, string containerName) => - GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).Get(); - /// /// Update a blob container /// @@ -119,33 +142,31 @@ public Track2.BlobContainerResource CreateBlobContainer(string resourceGroupName GetBlobContainers(resourceGroupName, storageAccountName).CreateOrUpdate(WaitUntil.Completed, containerName, data).Value; /// - /// Get immutability policy of a blob container - /// - public Track2.ImmutabilityPolicyResource GetImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, string etag) => - GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().Get(etag); - - /// - /// Lock immutability policy of a blob container + /// Get file share resource /// - public Track2.ImmutabilityPolicyResource LockImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, string etag) => - GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().LockImmutabilityPolicy(etag); + public Track2.FileShareResource GetFileShareResource(string resourceGroupName, string storageAccountName, string shareName) => + _armClient.GetFileShareResource(FileShareResource.CreateResourceIdentifier(_subscription, resourceGroupName, storageAccountName, shareName)); /// - /// Create immutability policy for a blob container + /// Get file service resource /// - public Track2.ImmutabilityPolicyResource CreateImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, ImmutabilityPolicyData data, string etag) => - GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().CreateOrUpdate(WaitUntil.Completed, data, etag).Value; + public Track2.FileServiceResource GetFileServiceResource(string resourceGroupName, string storageAccountName) => + _armClient.GetFileServiceResource(FileServiceResource.CreateResourceIdentifier(_subscription, resourceGroupName, storageAccountName)); /// - /// Extend immutability policy for a blob container + /// Get encryption scope resource /// - public Track2.ImmutabilityPolicyResource ExtendImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, ImmutabilityPolicyData data, string etag) => - GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().ExtendImmutabilityPolicy(etag, data); + public Track2.EncryptionScopeResource GetEncryptionScopeResource(string resourceGroupName, string accountName, string encryptionScopeName) => + _armClient.GetEncryptionScopeResource(EncryptionScopeResource.CreateResourceIdentifier(_subscription, resourceGroupName, accountName, encryptionScopeName)); /// - /// Delete immutability policy for a blob container + /// Get object replication policy resource /// - public Track2.ImmutabilityPolicyResource DeleteImmutabilityPolicy(string resourceGroupName, string storageAccountName, string containerName, string etag) => - GetBlobContainerResource(resourceGroupName, storageAccountName, containerName).GetImmutabilityPolicy().Delete(WaitUntil.Completed, etag).Value; + /// + /// + /// + /// + public Track2.ObjectReplicationPolicyResource GetObjectReplicationPolicyResource(string resourceGroupName, string storageAccountName, string policyId) => + _armClient.GetObjectReplicationPolicyResource(ObjectReplicationPolicyResource.CreateResourceIdentifier(_subscription, resourceGroupName, storageAccountName, policyId)); } } \ No newline at end of file From 02a29dfcdf9a0acf755d2dfb437372304d48a768 Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Mon, 6 Jun 2022 10:36:34 +0800 Subject: [PATCH 05/11] fix per comments --- .../Storage.Management/Models/PSDataPolicy.cs | 2 +- .../Storage.Management.csproj | 9 -- ...moveAzureStorageAccountManagementPolicy.cs | 2 +- .../RestoreAzStorageBlobRange.cs | 98 +++++++++++-------- .../SetAzureStorageAccountManagementPolicy.cs | 10 +- .../StorageAccountBaseCmdlet.cs | 6 +- 6 files changed, 70 insertions(+), 57 deletions(-) diff --git a/src/Storage/Storage.Management/Models/PSDataPolicy.cs b/src/Storage/Storage.Management/Models/PSDataPolicy.cs index 3f1431ebcb74..f71822f7a880 100644 --- a/src/Storage/Storage.Management/Models/PSDataPolicy.cs +++ b/src/Storage/Storage.Management/Models/PSDataPolicy.cs @@ -396,7 +396,7 @@ public Track2.Models.DateAfterModification ParseDateAfterModification() Track2.Models.DateAfterModification dateAfterModification = new Track2.Models.DateAfterModification(); dateAfterModification.DaysAfterLastAccessTimeGreaterThan = this.DaysAfterLastAccessTimeGreaterThan; dateAfterModification.DaysAfterModificationGreaterThan = this.DaysAfterModificationGreaterThan; - + // TODO: Add DaysAfterLastTierChangeGreaterThan once supported by Track2 SDK return dateAfterModification; } diff --git a/src/Storage/Storage.Management/Storage.Management.csproj b/src/Storage/Storage.Management/Storage.Management.csproj index af2abb9c9c5f..035a93d0bd02 100644 --- a/src/Storage/Storage.Management/Storage.Management.csproj +++ b/src/Storage/Storage.Management/Storage.Management.csproj @@ -13,15 +13,6 @@ $(AzAssemblyPrefix)$(PsModuleName).Management $(LegacyAssemblyPrefix)$(PsModuleName) - - - - - - - - - diff --git a/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccountManagementPolicy.cs b/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccountManagementPolicy.cs index 8481b536d316..21aa7877b98a 100644 --- a/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccountManagementPolicy.cs +++ b/src/Storage/Storage.Management/StorageAccount/RemoveAzureStorageAccountManagementPolicy.cs @@ -12,11 +12,11 @@ // limitations under the License. // ---------------------------------------------------------------------------------- +using Azure; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; using System.Management.Automation; -using Azure; namespace Microsoft.Azure.Commands.Management.Storage { diff --git a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs index 317de42e34c2..006c4d533cab 100644 --- a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs +++ b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs @@ -12,17 +12,18 @@ // limitations under the License. // ---------------------------------------------------------------------------------- -using Track2 = Azure.ResourceManager.Storage; -using Track2Models = Azure.ResourceManager.Storage.Models; +using Azure; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; using Microsoft.Rest.Azure; +using Microsoft.WindowsAzure.Commands.Utilities.Common; using System; using System.Collections.Generic; using System.Management.Automation; using System.Threading.Tasks; -using Azure; +using Track2 = Azure.ResourceManager.Storage; +using Track2Models = Azure.ResourceManager.Storage.Models; namespace Microsoft.Azure.Commands.Management.Storage { @@ -127,19 +128,19 @@ public override void ExecuteCmdlet() WaitUntil.Started, new Track2Models.BlobRestoreContent( this.TimeToRestore, - ParseBlobRestoreRanges(this.BlobRestoreRange)) + PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange)) ); - Dictionary temp = (Dictionary)restoreLro.GetRawResponse().Content.ToObjectFromJson(); + Dictionary temp = restoreLro.GetRawResponse().Content.ToObjectFromJson() as Dictionary; object restoreId; - if (temp.TryGetValue("restoreId", out restoreId)) + if (temp != null && temp.TryGetValue("restoreId", out restoreId)) { WriteWarning(string.Format("Restore blob ranges with Id '{0}' started. Restore blob ranges time to complete is dependent on the size of the restore.", restoreId)); } else { - WriteWarning(string.Format("Restore blob ranges with Id started. Restore blob ranges time to complete is dependent on the size of the restore.")); + WriteWarning(string.Format("Could not fetch the Restore Id.")); } try @@ -147,7 +148,7 @@ public override void ExecuteCmdlet() var result = restoreLro.WaitForCompletion().Value; WriteObject(new PSBlobRestoreStatus(result)); } - catch (Exception ex) + catch (System.AggregateException ex) when (ex.InnerException is CloudException) { throw new InvalidJobStateException(string.Format("Blob ranges restore failed with information: '{0}'.", ex.ToString())); } @@ -156,45 +157,62 @@ public override void ExecuteCmdlet() { Track2.StorageAccountResource account = this.StorageClientTrack2.GetStorageAccount(this.ResourceGroupName, this.StorageAccountName); var restoreLro = account.RestoreBlobRanges( - WaitUntil.Completed, + WaitUntil.Started, new Track2Models.BlobRestoreContent( this.TimeToRestore.ToUniversalTime(), - ParseBlobRestoreRanges(this.BlobRestoreRange))); - if (restoreLro.Value != null && restoreLro.Value.Status != null && restoreLro.Value.Status == Track2Models.BlobRestoreProgressStatus.Failed) + PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange))); + Dictionary temp = restoreLro.GetRawResponse().Content.ToObjectFromJson() as Dictionary; + object jobStatus = null; + + if (temp != null && temp.TryGetValue("status", out jobStatus)) + { + if (jobStatus != null && jobStatus.ToString() == Track2Models.BlobRestoreProgressStatus.Failed.ToString()) + { + throw new InvalidJobStateException("Blob ranges restore failed."); + } + } else { - throw new InvalidJobStateException("Blob ranges restore failed."); + WriteWarning(string.Format("Could not fetch the status.")); } - WriteObject(new PSBlobRestoreStatus(restoreLro.Value)); - } - } - } - /// - /// Parse from PSBlobRestoreRange list to BlobRestoreRange list - /// - public static IList ParseBlobRestoreRanges(PSBlobRestoreRange[] ranges) - { - IList re = new List(); - if (ranges == null) - { - re.Add( - new Track2Models.BlobRestoreRange( - startRange: "", - endRange: "" - )); - } - else - { - foreach (PSBlobRestoreRange range in ranges) - { - re.Add( - new Track2Models.BlobRestoreRange( - startRange: range.StartRange, - endRange: range.EndRange - )); + temp.TryGetValue("restoreId", out object restoreId); + temp.TryGetValue("parameters", out object parameters); + + PSBlobRestoreParameters blobRestoreParameters = new PSBlobRestoreParameters(); + Dictionary paramMap = parameters as Dictionary; + + paramMap.TryGetValue("timetoRestore", out object timeToRestore); + DateTimeOffset.TryParse(timeToRestore.ToString(), out DateTimeOffset parseDate); + blobRestoreParameters.TimeToRestore = parseDate; + + paramMap.TryGetValue("blobRanges", out object ranges); + List blobRestoreRanges = new List(); + + object[] rangesList = ranges as object[]; + foreach(object range in rangesList) + { + Dictionary rangeMap = range as Dictionary; + + rangeMap.TryGetValue("startRange", out object startRange); + rangeMap.TryGetValue("endRange", out object endRange); + + PSBlobRestoreRange blobRestoreRange = new PSBlobRestoreRange + { + StartRange = startRange == null ? null : startRange.ToString(), + EndRange = endRange == null ? null : endRange.ToString() + }; + + blobRestoreRanges.Add(blobRestoreRange); + } + blobRestoreParameters.BlobRanges = blobRestoreRanges.ToArray(); + + WriteObject(new PSBlobRestoreStatus( + status: jobStatus == null ? null : jobStatus.ToString(), + failureReason: null, + restoreId: restoreId == null ? null : restoreId.ToString(), + blobRestoreParameters)); } } - return re; } } } diff --git a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccountManagementPolicy.cs b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccountManagementPolicy.cs index 1c3527158d68..8e7b64c8d91f 100644 --- a/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccountManagementPolicy.cs +++ b/src/Storage/Storage.Management/StorageAccount/SetAzureStorageAccountManagementPolicy.cs @@ -12,16 +12,16 @@ // limitations under the License. // ---------------------------------------------------------------------------------- +using Azure.ResourceManager.Storage; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; -using System.Management.Automation; -using Newtonsoft.Json.Linq; -using System.Globalization; -using System.Collections.Generic; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; +using Newtonsoft.Json.Linq; +using System.Collections.Generic; +using System.Globalization; +using System.Management.Automation; using Track2 = Azure.ResourceManager.Storage; -using Azure.ResourceManager.Storage; namespace Microsoft.Azure.Commands.Management.Storage { diff --git a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs index 9a50e7200c66..b2722327a996 100644 --- a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs +++ b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs @@ -221,7 +221,11 @@ public static CloudStorageAccount GetCloudStorageAccount(Track2.StorageAccountRe Uri queueEndpoint = storageAccountResource.Data.PrimaryEndpoints.Queue != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.Queue) : null; Uri tableEndpoint = storageAccountResource.Data.PrimaryEndpoints.Table != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.Table) : null; Uri fileEndpoint = storageAccountResource.Data.PrimaryEndpoints.File != null ? new Uri(storageAccountResource.Data.PrimaryEndpoints.File) : null; - string key = storageAccountResource.GetKeys().Value.Keys[0].Value; + string key = null; + if (storageAccountResource.GetKeys()?.Value?.Keys != null && storageAccountResource.GetKeys().Value.Keys.Count > 0) + { + key = storageAccountResource.GetKeys().Value.Keys[0].Value; + } StorageCredentials storageCredentials = new Azure.Storage.Auth.StorageCredentials(storageAccountResource.Data.Name, key); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount( storageCredentials, From ae29774dce6ea982d8b4aad4093cda72cdad840e Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Mon, 6 Jun 2022 10:45:28 +0800 Subject: [PATCH 06/11] Add a new constrcutor in PSBlobRestore --- src/Storage/Storage.Management/Models/PSBlobRestore.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Storage/Storage.Management/Models/PSBlobRestore.cs b/src/Storage/Storage.Management/Models/PSBlobRestore.cs index 33384b2d60a6..b0609e3ccff7 100644 --- a/src/Storage/Storage.Management/Models/PSBlobRestore.cs +++ b/src/Storage/Storage.Management/Models/PSBlobRestore.cs @@ -57,7 +57,7 @@ public PSBlobRestoreRange(Track2Models.BlobRestoreRange range) foreach (PSBlobRestoreRange range in ranges) { re.Add( - new Track2Models.BlobRestoreRange(range.EndRange, range.StartRange)); + new Track2Models.BlobRestoreRange(range.StartRange, range.EndRange)); } } return re; @@ -112,6 +112,14 @@ public PSBlobRestoreStatus(Track2Models.BlobRestoreStatus status) this.Parameters = status.Parameters is null ? null : new PSBlobRestoreParameters(status.Parameters); } } + + public PSBlobRestoreStatus(string status, string failureReason, string restoreId, PSBlobRestoreParameters parameters) + { + Status = status; + FailureReason = failureReason; + RestoreId = restoreId; + Parameters = parameters; + } } /// From f31835f053e36fbcda87cc92dd0461c08c3364b3 Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Mon, 6 Jun 2022 20:55:31 +0800 Subject: [PATCH 07/11] fix per comments --- .../Storage.Management/Models/PSDataPolicy.cs | 19 ++++++++++--------- .../RestoreAzStorageBlobRange.cs | 18 +++++++++++++----- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/Storage/Storage.Management/Models/PSDataPolicy.cs b/src/Storage/Storage.Management/Models/PSDataPolicy.cs index f71822f7a880..eb9aa93727a1 100644 --- a/src/Storage/Storage.Management/Models/PSDataPolicy.cs +++ b/src/Storage/Storage.Management/Models/PSDataPolicy.cs @@ -79,7 +79,7 @@ public Track2.Models.ManagementPolicyRule ParseManagementPolicyRule() Track2.Models.ManagementPolicyRule rule = new Track2.Models.ManagementPolicyRule( this.Name, RuleType.Lifecycle, - this.Definition is null ? null : this.Definition.ParseManagementPolicyDefination() + this.Definition?.ParseManagementPolicyDefination() ); rule.Enabled = this.Enabled; return rule; @@ -133,9 +133,9 @@ public PSManagementPolicyDefinition(Track2.Models.ManagementPolicyDefinition def } public Track2.Models.ManagementPolicyDefinition ParseManagementPolicyDefination() { - Track2.Models.ManagementPolicyAction actions = this.Actions is null ? null : this.Actions.ParseManagementPolicyAction(); + Track2.Models.ManagementPolicyAction actions = this.Actions?.ParseManagementPolicyAction(); Track2.Models.ManagementPolicyDefinition policyDefinition = new Track2.Models.ManagementPolicyDefinition(actions); - policyDefinition.Filters = this.Filters is null ? null : this.Filters.ParseManagementPolicyFilter(); + policyDefinition.Filters = this.Filters?.ParseManagementPolicyFilter(); return policyDefinition; } @@ -219,9 +219,9 @@ public Track2.Models.ManagementPolicyAction ParseManagementPolicyAction() { return new Track2.Models.ManagementPolicyAction() { - BaseBlob = this.BaseBlob is null ? null : this.BaseBlob.ParseManagementPolicyBaseBlob(), - Snapshot = this.Snapshot is null ? null : this.Snapshot.ParseManagementPolicySnapShot(), - Version = this.Version is null ? null : this.Version.ParseManagementPolicyVersion(), + BaseBlob = this.BaseBlob?.ParseManagementPolicyBaseBlob(), + Snapshot = this.Snapshot?.ParseManagementPolicySnapShot(), + Version = this.Version?.ParseManagementPolicyVersion(), }; } } @@ -250,9 +250,9 @@ public Track2.Models.ManagementPolicyBaseBlob ParseManagementPolicyBaseBlob() { return new Track2.Models.ManagementPolicyBaseBlob() { - TierToCool = this.TierToCool is null ? null : this.TierToCool.ParseDateAfterModification(), - TierToArchive = this.TierToArchive is null ? null : this.TierToArchive.ParseDateAfterModification(), - Delete = this.Delete is null ? null : this.Delete.ParseDateAfterModification(), + TierToCool = this.TierToCool?.ParseDateAfterModification(), + TierToArchive = this.TierToArchive?.ParseDateAfterModification(), + Delete = this.Delete?.ParseDateAfterModification(), EnableAutoTierToHotFromCool = this.EnableAutoTierToHotFromCool }; } @@ -345,6 +345,7 @@ public class PSDateAfterModification public int? DaysAfterModificationGreaterThan { get; set; } public int? DaysAfterLastAccessTimeGreaterThan { get; set; } + // TODO: DaysAfterLastTierChangeGreaterThan it not supported by SDK yet. Will add later. public int? DaysAfterLastTierChangeGreaterThan { get; set; } public PSDateAfterModification() diff --git a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs index 006c4d533cab..4a3031c7f5b8 100644 --- a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs +++ b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs @@ -131,6 +131,9 @@ public override void ExecuteCmdlet() PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange)) ); + // This is a temporary workaround of SDK issue https://github.com/Azure/azure-sdk-for-net/issues/29060 + // The workaround is to get the raw response and parse it into the output desired + // The Blob restore status should be got from SDK directly once the issue is fixed Dictionary temp = restoreLro.GetRawResponse().Content.ToObjectFromJson() as Dictionary; object restoreId; @@ -175,12 +178,17 @@ public override void ExecuteCmdlet() WriteWarning(string.Format("Could not fetch the status.")); } + if (temp == null) + { + throw new InvalidJobStateException("Could not fetch the Blob restore response."); + } + temp.TryGetValue("restoreId", out object restoreId); temp.TryGetValue("parameters", out object parameters); PSBlobRestoreParameters blobRestoreParameters = new PSBlobRestoreParameters(); Dictionary paramMap = parameters as Dictionary; - + paramMap.TryGetValue("timetoRestore", out object timeToRestore); DateTimeOffset.TryParse(timeToRestore.ToString(), out DateTimeOffset parseDate); blobRestoreParameters.TimeToRestore = parseDate; @@ -198,8 +206,8 @@ public override void ExecuteCmdlet() PSBlobRestoreRange blobRestoreRange = new PSBlobRestoreRange { - StartRange = startRange == null ? null : startRange.ToString(), - EndRange = endRange == null ? null : endRange.ToString() + StartRange = startRange?.ToString(), + EndRange = endRange?.ToString() }; blobRestoreRanges.Add(blobRestoreRange); @@ -207,9 +215,9 @@ public override void ExecuteCmdlet() blobRestoreParameters.BlobRanges = blobRestoreRanges.ToArray(); WriteObject(new PSBlobRestoreStatus( - status: jobStatus == null ? null : jobStatus.ToString(), + status: jobStatus?.ToString(), failureReason: null, - restoreId: restoreId == null ? null : restoreId.ToString(), + restoreId: restoreId?.ToString(), blobRestoreParameters)); } } From dd5e036f85cfc51c62858d99647f4707e0a83025 Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Wed, 8 Jun 2022 11:09:05 +0800 Subject: [PATCH 08/11] add comments --- .../Storage.Management/Models/PSDataPolicy.cs | 2 ++ .../Storage.Management/Storage.Management.csproj | 7 +++++++ .../StorageAccount/StorageAccountBaseCmdlet.cs | 12 ++++++++---- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/Storage/Storage.Management/Models/PSDataPolicy.cs b/src/Storage/Storage.Management/Models/PSDataPolicy.cs index eb9aa93727a1..6f17877168f3 100644 --- a/src/Storage/Storage.Management/Models/PSDataPolicy.cs +++ b/src/Storage/Storage.Management/Models/PSDataPolicy.cs @@ -412,6 +412,8 @@ public class PSDateAfterCreation public int DaysAfterCreationGreaterThan { get; set; } public int? DaysAfterLastTierChangeGreaterThan { get; set; } + // TODO: DaysAfterLastTierChangeGreaterThan is still not supported by SDK, will add later. + public PSDateAfterCreation() { this.DaysAfterCreationGreaterThan = 0; diff --git a/src/Storage/Storage.Management/Storage.Management.csproj b/src/Storage/Storage.Management/Storage.Management.csproj index 035a93d0bd02..e1ba21feca76 100644 --- a/src/Storage/Storage.Management/Storage.Management.csproj +++ b/src/Storage/Storage.Management/Storage.Management.csproj @@ -13,6 +13,13 @@ $(AzAssemblyPrefix)$(PsModuleName).Management $(LegacyAssemblyPrefix)$(PsModuleName) + + + + + + + diff --git a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs index b2722327a996..b5312c54ed00 100644 --- a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs +++ b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs @@ -15,18 +15,19 @@ using Azure.Core; using Azure.ResourceManager; using Azure.ResourceManager.Resources; -using Track2 = Azure.ResourceManager.Storage; -using Track2Models = Azure.ResourceManager.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; +using Microsoft.Azure.Storage; +using Microsoft.Azure.Storage.Auth; using Microsoft.WindowsAzure.Commands.Utilities.Common; using System; using System.Collections.Generic; +using System.Management.Automation; using StorageModels = Microsoft.Azure.Management.Storage.Models; -using Microsoft.Azure.Storage; -using Microsoft.Azure.Storage.Auth; +using Track2 = Azure.ResourceManager.Storage; +using Track2Models = Azure.ResourceManager.Storage.Models; namespace Microsoft.Azure.Commands.Management.Storage { @@ -225,6 +226,9 @@ public static CloudStorageAccount GetCloudStorageAccount(Track2.StorageAccountRe if (storageAccountResource.GetKeys()?.Value?.Keys != null && storageAccountResource.GetKeys().Value.Keys.Count > 0) { key = storageAccountResource.GetKeys().Value.Keys[0].Value; + } else + { + throw new InvalidJobStateException("Could not fetch keys."); } StorageCredentials storageCredentials = new Azure.Storage.Auth.StorageCredentials(storageAccountResource.Data.Name, key); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount( From fcfd28cf1687e1327294288ad1691eb937ad87d9 Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Wed, 8 Jun 2022 11:53:53 +0800 Subject: [PATCH 09/11] fix per comments --- src/Storage/Storage.Management/Storage.Management.csproj | 1 + .../StorageAccount/StorageAccountBaseCmdlet.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Storage/Storage.Management/Storage.Management.csproj b/src/Storage/Storage.Management/Storage.Management.csproj index e1ba21feca76..a4f7615c7603 100644 --- a/src/Storage/Storage.Management/Storage.Management.csproj +++ b/src/Storage/Storage.Management/Storage.Management.csproj @@ -19,6 +19,7 @@ + diff --git a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs index b5312c54ed00..221d25154a6f 100644 --- a/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs +++ b/src/Storage/Storage.Management/StorageAccount/StorageAccountBaseCmdlet.cs @@ -228,7 +228,7 @@ public static CloudStorageAccount GetCloudStorageAccount(Track2.StorageAccountRe key = storageAccountResource.GetKeys().Value.Keys[0].Value; } else { - throw new InvalidJobStateException("Could not fetch keys."); + throw new InvalidJobStateException("Could not fetch storage account keys to build storage account context."); } StorageCredentials storageCredentials = new Azure.Storage.Auth.StorageCredentials(storageAccountResource.Data.Name, key); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount( From 43db5f363ee00664e79e5e1e005aafb7ed90482a Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Thu, 9 Jun 2022 17:45:40 +0800 Subject: [PATCH 10/11] put parser into helper --- .../RestoreAzStorageBlobRange.cs | 101 +++++++++++------- 1 file changed, 60 insertions(+), 41 deletions(-) diff --git a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs index 4a3031c7f5b8..2f47f89875e2 100644 --- a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs +++ b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs @@ -135,11 +135,15 @@ public override void ExecuteCmdlet() // The workaround is to get the raw response and parse it into the output desired // The Blob restore status should be got from SDK directly once the issue is fixed Dictionary temp = restoreLro.GetRawResponse().Content.ToObjectFromJson() as Dictionary; - object restoreId; - if (temp != null && temp.TryGetValue("restoreId", out restoreId)) + if (temp == null) + { + throw new InvalidJobStateException("Could not fetch the Blob restore response."); + } + PSBlobRestoreStatus blobRestoreStatus = ParseRestoreRawResponse(temp); + if (blobRestoreStatus.RestoreId != null) { - WriteWarning(string.Format("Restore blob ranges with Id '{0}' started. Restore blob ranges time to complete is dependent on the size of the restore.", restoreId)); + WriteWarning(string.Format("Restore blob ranges with Id '{0}' started. Restore blob ranges time to complete is dependent on the size of the restore.", blobRestoreStatus.RestoreId)); } else { @@ -165,62 +169,77 @@ public override void ExecuteCmdlet() this.TimeToRestore.ToUniversalTime(), PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange))); Dictionary temp = restoreLro.GetRawResponse().Content.ToObjectFromJson() as Dictionary; - object jobStatus = null; - if (temp != null && temp.TryGetValue("status", out jobStatus)) + if (temp == null) + { + throw new InvalidJobStateException("Could not fetch the Blob restore response."); + } + + PSBlobRestoreStatus blobRestoreStatus = ParseRestoreRawResponse(temp); + + if (blobRestoreStatus.Status != null) { - if (jobStatus != null && jobStatus.ToString() == Track2Models.BlobRestoreProgressStatus.Failed.ToString()) + if (blobRestoreStatus.Status == Track2Models.BlobRestoreProgressStatus.Failed.ToString()) { throw new InvalidJobStateException("Blob ranges restore failed."); } - } else + } + else { WriteWarning(string.Format("Could not fetch the status.")); } + WriteObject(blobRestoreStatus); + } + } + } - if (temp == null) - { - throw new InvalidJobStateException("Could not fetch the Blob restore response."); - } + private PSBlobRestoreStatus ParseRestoreRawResponse(Dictionary response) + { + response.TryGetValue("restoreId", out object restoreId); + response.TryGetValue("status", out object jobStatus); + response.TryGetValue("parameters", out object parameters); - temp.TryGetValue("restoreId", out object restoreId); - temp.TryGetValue("parameters", out object parameters); + PSBlobRestoreParameters blobRestoreParameters; + Dictionary paramMap = parameters as Dictionary; - PSBlobRestoreParameters blobRestoreParameters = new PSBlobRestoreParameters(); - Dictionary paramMap = parameters as Dictionary; + if (paramMap == null) + { + blobRestoreParameters = null; + } + else + { + blobRestoreParameters = new PSBlobRestoreParameters(); + paramMap.TryGetValue("timetoRestore", out object timeToRestore); + DateTimeOffset.TryParse(timeToRestore?.ToString(), out DateTimeOffset parseDate); + blobRestoreParameters.TimeToRestore = parseDate; - paramMap.TryGetValue("timetoRestore", out object timeToRestore); - DateTimeOffset.TryParse(timeToRestore.ToString(), out DateTimeOffset parseDate); - blobRestoreParameters.TimeToRestore = parseDate; + paramMap.TryGetValue("blobRanges", out object ranges); + List blobRestoreRanges = new List(); - paramMap.TryGetValue("blobRanges", out object ranges); - List blobRestoreRanges = new List(); - - object[] rangesList = ranges as object[]; - foreach(object range in rangesList) - { - Dictionary rangeMap = range as Dictionary; - - rangeMap.TryGetValue("startRange", out object startRange); - rangeMap.TryGetValue("endRange", out object endRange); + object[] rangesList = ranges as object[]; + foreach (object range in rangesList) + { + Dictionary rangeMap = range as Dictionary; - PSBlobRestoreRange blobRestoreRange = new PSBlobRestoreRange - { - StartRange = startRange?.ToString(), - EndRange = endRange?.ToString() - }; + rangeMap.TryGetValue("startRange", out object startRange); + rangeMap.TryGetValue("endRange", out object endRange); - blobRestoreRanges.Add(blobRestoreRange); - } - blobRestoreParameters.BlobRanges = blobRestoreRanges.ToArray(); + PSBlobRestoreRange blobRestoreRange = new PSBlobRestoreRange + { + StartRange = startRange?.ToString(), + EndRange = endRange?.ToString() + }; - WriteObject(new PSBlobRestoreStatus( - status: jobStatus?.ToString(), - failureReason: null, - restoreId: restoreId?.ToString(), - blobRestoreParameters)); + blobRestoreRanges.Add(blobRestoreRange); } + blobRestoreParameters.BlobRanges = blobRestoreRanges.ToArray(); } + + return new PSBlobRestoreStatus( + status: jobStatus?.ToString(), + failureReason: null, + restoreId: restoreId?.ToString(), + parameters: blobRestoreParameters); } } } From 0fc210d5d5004982b41170e48d637db7a1f6f89d Mon Sep 17 00:00:00 2001 From: Yifan Zhang Date: Thu, 9 Jun 2022 18:58:56 +0800 Subject: [PATCH 11/11] move common code outside of if-else --- .../RestoreAzStorageBlobRange.cs | 33 +++++++------------ 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs index 2f47f89875e2..d0aa229636d2 100644 --- a/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs +++ b/src/Storage/Storage.Management/StorageAccount/RestoreAzStorageBlobRange.cs @@ -121,21 +121,20 @@ public override void ExecuteCmdlet() if (ShouldProcess(this.StorageAccountName, "Restore Blob Range")) { + Track2.StorageAccountResource account = this.StorageClientTrack2.GetStorageAccount(this.ResourceGroupName, this.StorageAccountName); + var restoreLro = account.RestoreBlobRanges( + WaitUntil.Started, + new Track2Models.BlobRestoreContent( + this.TimeToRestore.ToUniversalTime(), + PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange))); + + // This is a temporary workaround of SDK issue https://github.com/Azure/azure-sdk-for-net/issues/29060 + // The workaround is to get the raw response and parse it into the output desired + // The Blob restore status should be got from SDK directly once the issue is fixed + Dictionary temp = restoreLro.GetRawResponse().Content.ToObjectFromJson() as Dictionary; + if (waitForComplete) { - Track2.StorageAccountResource account = this.StorageClientTrack2.GetStorageAccount(this.ResourceGroupName, this.StorageAccountName); - var restoreLro = account.RestoreBlobRanges( - WaitUntil.Started, - new Track2Models.BlobRestoreContent( - this.TimeToRestore, - PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange)) - ); - - // This is a temporary workaround of SDK issue https://github.com/Azure/azure-sdk-for-net/issues/29060 - // The workaround is to get the raw response and parse it into the output desired - // The Blob restore status should be got from SDK directly once the issue is fixed - Dictionary temp = restoreLro.GetRawResponse().Content.ToObjectFromJson() as Dictionary; - if (temp == null) { throw new InvalidJobStateException("Could not fetch the Blob restore response."); @@ -162,14 +161,6 @@ public override void ExecuteCmdlet() } else { - Track2.StorageAccountResource account = this.StorageClientTrack2.GetStorageAccount(this.ResourceGroupName, this.StorageAccountName); - var restoreLro = account.RestoreBlobRanges( - WaitUntil.Started, - new Track2Models.BlobRestoreContent( - this.TimeToRestore.ToUniversalTime(), - PSBlobRestoreRange.ParseBlobRestoreRanges(this.BlobRestoreRange))); - Dictionary temp = restoreLro.GetRawResponse().Content.ToObjectFromJson() as Dictionary; - if (temp == null) { throw new InvalidJobStateException("Could not fetch the Blob restore response.");