Skip to content

Tab completer for existing resources (Iss #5415) #6163

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Threading;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Management.Internal.Resources;
using Microsoft.Azure.Management.Internal.Resources.Models;
using Microsoft.Rest.Azure.OData;

namespace Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class ResourceIdCompleterAttribute : ArgumentCompleterAttribute
{
private static readonly object Lock = new object();

/// <summary>
/// Consturctor
/// </summary>
/// <param name="resourceType">Azure recource type</param>
public ResourceIdCompleterAttribute(string resourceType)
: base(CreateScriptBlock(resourceType))
{}

public static ScriptBlock CreateScriptBlock(string resourceType)
{
string script = "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)\n" +
$"$resourceType = \"{resourceType}\"\n" +
"$resourceIds = [Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters.ResourceIdCompleterAttribute]::GetResourceIds($resourceType)\n" +
"$resourceIds | Where-Object { $_ -Like \"*$wordToComplete*\" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }";
var scriptBlock = ScriptBlock.Create(script);
return scriptBlock;
}

private class CacheItem
{
public DateTime Timestamp { get; set; }
public IEnumerable<string> ResourceInfoList { get; set; }
}

private static readonly IDictionary<int, CacheItem> Cache = new Dictionary<int, CacheItem>();

public static TimeSpan TimeToUpdate { get; set; } = TimeSpan.FromMinutes(5);

public static TimeSpan RequestTimeout { get; set; } = TimeSpan.FromSeconds(3);

public static IEnumerable<string> GetResourceIds(string resourceType)
{
lock (Lock)
{
var context = AzureRmProfileProvider.Instance.Profile.DefaultContext;
var contextHash = HashContext(context, resourceType);
var cacheItem = Cache.ContainsKey(contextHash) ? Cache[contextHash] : null;

if (cacheItem != null && DateTime.Now.Subtract(cacheItem.Timestamp).CompareTo(TimeToUpdate) < 0)
{
return Cache[contextHash].ResourceInfoList;
}

var client = AzureSession.Instance.ClientFactory.CreateArmClient<ResourceManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager);

var odata = new ODataQuery<GenericResourceFilter>(r => r.ResourceType == resourceType);

IEnumerable<string> resourceInfoList = new List<string>();

try
{
using (var cancelSource = new CancellationTokenSource())
{
var task = client.Resources.ListAsync(odata, cancelSource.Token);

if (!task.Wait(RequestTimeout))
{
cancelSource.Cancel();
return resourceInfoList;
}

var result = task.Result;
resourceInfoList = result
.Select(r => r.Id)
.ToList();
}
}
catch (Exception)
{
return resourceInfoList;
}

if (cacheItem != null)
{
cacheItem.Timestamp = DateTime.Now;
cacheItem.ResourceInfoList = resourceInfoList;
Cache[contextHash] = cacheItem;
}
else
{
Cache.Add(contextHash, new CacheItem
{
Timestamp = DateTime.Now,
ResourceInfoList = resourceInfoList
});
}

return resourceInfoList;
}
}

private static int HashContext(IAzureContext context, string resourceType)
{
return (context.Account.Id + context.Environment.Name + context.Subscription.Id + context.Tenant.Id + resourceType).GetHashCode();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
<ItemGroup>
<Compile Include="AccessTokenExtensions.cs" />
<Compile Include="ArgumentCompleters\PSArgumentCompleter.cs" />
<Compile Include="ArgumentCompleters\ResourceIdCompleter.cs" />
<Compile Include="ArgumentCompleters\ResourceTypeCompleter.cs" />
<Compile Include="ArgumentCompleters\ScopeCompleter.cs" />
<Compile Include="AzureRmCmdlet.cs" />
Expand Down
1 change: 1 addition & 0 deletions src/ResourceManager/Compute/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
## Current Release

## Version 5.1.1
* ResourceId tab completer applied to the cmdelts top level resource id parameters if any.
* `Get-AzureRmVmDiskEncryptionStatus` fixes an issue observed for VMs with no data disks
* Update Compute client library version to fix following cmdlets
- Grant-AzureRmDiskAccess
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public class RestartAzureVMCommand : VirtualMachineBaseCmdlet
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
[ResourceIdCompleter("Microsoft.Compute/virtualMachines")]
public string Id { get; set; }


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public class SetAzureVMCommand : VirtualMachineBaseCmdlet
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
[ResourceIdCompleter("Microsoft.Compute/virtualMachines")]
public string Id { get; set; }

[Parameter(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public abstract class VirtualMachineActionBaseCmdlet : VirtualMachineBaseCmdlet
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
[ResourceIdCompleter("Microsoft.Compute/virtualMachines")]
public string Id { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ public class UpdateAzureVMCommand : VirtualMachineBaseCmdlet
ParameterSetName = IdParameterSet,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ResourceIdCompleter("Microsoft.Compute/virtualMachines")]
public string Id { get; set; }

[Alias("VMProfile")]
Expand Down
1 change: 1 addition & 0 deletions src/ResourceManager/Profile/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
## Version 5.3.0
* Updated error messages for Enable-AzureRmContextAutoSave
* Create a context for each subscription when running `Connect-AzureRmAccount` with no previous context
* Resource Id completer added.

## Version 5.2.0
* Added the following three values to the telemetry:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,12 @@ public void TestResourceGroupCompleter()
{
ProfileController.NewInstance.RunPsTest(xunitLogger, "72f988bf-86f1-41af-91ab-2d7cd011db47", "Test-ResourceGroupCompleter");
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestResourceIdCompleter()
{
ProfileController.NewInstance.RunPsTest(xunitLogger, "72f988bf-86f1-41af-91ab-2d7cd011db47", "Test-ResourceIdCompleter");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,27 @@ function Test-ResourceGroupCompleter
$resourceGroups = [Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters.ResourceGroupCompleterAttribute]::GetResourceGroups(-1)
$expectResourceGroups = Get-AzureRmResourceGroup | ForEach-Object {$_.ResourceGroupName}
Assert-AreEqualArray $resourceGroups $expectResourceGroups
}

<#
.SYNOPSIS
Tests resource id completer
#>
function Test-ResourceIdCompleter
{
$filePath = Join-Path -Path $PSScriptRoot -ChildPath "\Microsoft.Azure.Commands.ResourceManager.Common.dll"
[System.Reflection.Assembly]::LoadFrom($filePath)
$resourceType = "Microsoft.Storage/storageAccounts"
$expectResourceIds = Get-AzureRmResource -ResourceType $resourceType | ForEach-Object {$_.Id}
# take data from Azure and put to cache
$resourceIds = [Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters.ResourceIdCompleterAttribute]::GetResourceIds($resourceType)
Assert-AreEqualArray $resourceIds $expectResourceIds
# take data from the cache
$resourceIds = [Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters.ResourceIdCompleterAttribute]::GetResourceIds($resourceType)
Assert-AreEqualArray $resourceIds $expectResourceIds
# change time to update the cache
[Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters.ResourceIdCompleterAttribute]::TimeToUpdate = [System.TimeSpan]::FromSeconds(0)
# take data from Azure again and put to cache
$resourceIds = [Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters.ResourceIdCompleterAttribute]::GetResourceIds($resourceType)
Assert-AreEqualArray $resourceIds $expectResourceIds
}
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,9 @@
<None Include="SessionRecords\Microsoft.Azure.Commands.Profile.Test.ArgumentCompleterTests\TestResourceGroupCompleter.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="SessionRecords\Microsoft.Azure.Commands.Profile.Test.ArgumentCompleterTests\TestResourceIdCompleter.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="SessionRecords\Microsoft.Azure.Commands.Profile.Test.DefaultCmdletTests\DefaultResourceGroup.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
Expand Down
Loading