Skip to content
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

Add prompt for usage and survey #13965

Merged
merged 13 commits into from
Feb 19, 2021
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ For more information on Az Predictor, please visit the following: https://aka.ms

<ItemGroup>
<None Include="Az.Tools.Predictor.psd1" CopyToOutputDirectory="PreserveNewest" />
<None Include="InterceptSurvey.ps1" CopyToOutputDirectory="PreserveNewest" />
<None Include="PromptSurvey.ps1" CopyToOutputDirectory="PreserveNewest" />
<None Include="AzPredictorSettings.json" CopyToOutputDirectory="PreserveNewest" />
<None Include="command_param_to_resource_map.json" CopyToOutputDirectory="PreserveNewest" />
<None Include="command_param_to_resource_map.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,11 @@ CompanyName = 'Microsoft Corporation'
Copyright = 'Microsoft Corporation. All rights reserved.'

# Description of the functionality provided by this module
Description = 'Microsoft Azure PowerShell - Module providing recommendations to PSReadLine v2.2.0 or above for cmdlets comprised in the Az module - This module is compatible with PowerShell 7.1 or above.
Description = 'Microsoft Azure PowerShell - Module providing recommendations for cmdlets comprised in the Az module - This module is compatible with PowerShell 7.2 or above.

The module needs to be imported manually via
Import-Module Az.Tools.Predictor

Enable plugins via
Set-PSReadLineOption -PredictionSource HistoryAndPlugin

Switch the output format of suggestions to list view via
Set-PSReadLineOption -PredictionViewStyle ListView
The suggestions must be activated:
- Enable-AzPredictor: Activate the suggestions
- Disable-AzPredictor: Disable the suggestions

For more information on Az Predictor, please visit the following: https://aka.ms/azpredictordocs'

Expand All @@ -50,6 +45,8 @@ PowerShellVersion = '7.1'

NestedModules = @("Microsoft.Azure.PowerShell.Tools.AzPredictor.dll")

ScriptsToProcess = @("PromptSurvey.ps1")

# Format files (.ps1xml) to be loaded when importing this module

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
Expand All @@ -58,7 +55,7 @@ PrivateData = @{
PSData = @{

# Tags applied to this module. These help with module discovery in online galleries.
Tags = 'Azure','PowerShell','Prediction'
Tags = 'Azure','PowerShell','Prediction', 'Recommendation', 'Az Predictor'
kceiw marked this conversation as resolved.
Show resolved Hide resolved

# A URL to the license for this module.
LicenseUri = 'https://aka.ms/azps-license'
Expand Down
15 changes: 14 additions & 1 deletion tools/Az.Tools.Predictor/Az.Tools.Predictor/AzContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ namespace Microsoft.Azure.PowerShell.Tools.AzPredictor
/// </summary>
internal sealed class AzContext : IAzContext
{
private const string InternalUserSuffix = "@microsoft.com";
private static readonly Version DefaultVersion = new Version("0.0.0.0");

/// <inheritdoc/>
Expand Down Expand Up @@ -100,13 +101,25 @@ public Version ModuleVersion
}
}

public bool IsInternal { get; internal set; }

internal string SurveyId { get; set; }
kceiw marked this conversation as resolved.
Show resolved Hide resolved

/// <inheritdoc/>
public void UpdateContext()
{
AzVersion = GetAzVersion();
UserId = GenerateSha256HashString(GetUserAccountId());
RawUserId = GetUserAccountId();
UserId = GenerateSha256HashString(RawUserId);

if (!IsInternal)
{
IsInternal = RawUserId.EndsWith(AzContext.InternalUserSuffix, StringComparison.OrdinalIgnoreCase);
}
}

internal string RawUserId { get; set; }

/// <summary>
/// Gets the user account id if the user logs in, otherwise empty string.
/// </summary>
Expand Down
8 changes: 7 additions & 1 deletion tools/Az.Tools.Predictor/Az.Tools.Predictor/AzPredictor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.Azure.PowerShell.Tools.AzPredictor.Utilities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
Expand Down Expand Up @@ -225,7 +226,12 @@ public class PredictorInitializer : IModuleAssemblyInitializer
public void OnImport()
{
var settings = Settings.GetSettings();
var azContext = new AzContext();
var azContext = new AzContext()
{
IsInternal = (settings.SetAsInternal == true) ? true : false,
SurveyId = settings.SurveyId?.ToString(CultureInfo.InvariantCulture) ?? string.Empty,
};

azContext.UpdateContext();
var telemetryClient = new AzPredictorTelemetryClient(azContext);
var azPredictorService = new AzPredictorService(settings.ServiceUri, telemetryClient, azContext);
Expand Down
5 changes: 5 additions & 0 deletions tools/Az.Tools.Predictor/Az.Tools.Predictor/IAzContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ internal interface IAzContext
/// </summary>
public Version AzVersion { get; }

/// <summary>
/// Gets whether the user is an internal user.
/// </summary>
public bool IsInternal { get; }

/// <summary>
/// Updates the Az context.
/// </summary>
Expand Down
204 changes: 204 additions & 0 deletions tools/Az.Tools.Predictor/Az.Tools.Predictor/InterceptSurvey.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.internal
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

param (
kceiw marked this conversation as resolved.
Show resolved Hide resolved
[Parameter(Mandatory)]
[string] $moduleName,
[Parameter(Mandatory)]
[int] $majorVersion
)

if ([string]::IsNullOrWhiteSpace($moduleName)) {
kceiw marked this conversation as resolved.
Show resolved Hide resolved
return
}

if ($majorVersion -lt 0) {
return
}

if ($env:Azure_PS_Intercept_Survey -eq "false") {
return
}

$mutexName = "AzModulesInterceptSurvey"
$mutexTiimeout = 1000
$interceptDays = 30
$interceptLoadTimes = 3
$today = Get-Date
$mutexTimeout = 500

function ConvertTo-String {
param (
[Parameter(Mandatory)]
[DateTime] $date
)

return $date.ToString("yyyy-MM-dd")
}

function Init-InterceptFile {
$interceptContent = @{
"lastInterceptCheckDate"=ConvertTo-String($today);
"interceptTriggered"=$false;
"modules"=@(@{
"name"=$moduleName;
"majorVersion"=$majorVersion;
"activeDays"=1;
"lastActiveDate"=ConvertTo-String($today);
})
}

ConvertTo-Json -InputObject $interceptContent | Out-File -FilePath $interceptFilePath -Encoding utf8
}

# Update the intercept object and return $true if we need to show the survey.
function Update-InterceptObject {
param (
$interceptObject
)

$thisModule = $null

foreach ($m in $interceptObject.modules) {
if ($m.name -eq $moduleName) {
$thisModule = $m
break
}
}

if ($thisModule -eq $null) {
# There is no information about this module. The file could be created by another module or in some other way.
# We need to add this module to the list.

$thisModule = @{
"name"=$moduleName;
"majorVersion"=$majorVersion;
"activeDays"=1;
"lastActiveDate"=ConvertTo-String($today);
}

$interceptObject.modules += $thisModule

return $false
}

$recordedMajorVersion = $thisModule.majorVersion
$thisModule.majorVersion = $majorVersion

if ($recordedMajorVersion -ne $majorVersion) {
$thisModule.activeDays = 1
$thisModule.lastActiveDate = ConvertTo-String($today)
$interceptObject.interceptTriggered = $false

return $false
}

$recordedLastActiveDate = Get-Date $thisModule.lastActiveDate
$recordedActiveDays = $thisModule.activeDays

$elapsedDays = ($today - $recordedLastActiveDate).Days

if ($elapsedDays -gt $interceptDays) {
$thisModule.activeDays = 1
$thisModule.lastActiveDate = ConvertTo-String($today)

return $false
}

$newActiveDays = $recordedActiveDays

if ($elapsedDays -ne 0) {
$newActiveDays++
}

if ($newActiveDays -ge $interceptLoadTimes) {
$thisModule.activeDays = 0
$thisModule.lastActiveDate = ConvertTo-String($today)
$interceptObject.interceptTriggered = $true
return $true
}

$thisModule.activeDays = $newActiveDays
$thisModule.lastActiveDate = ConvertTo-String($today)
}

$mutex = New-Object System.Threading.Mutex($false, $mutexName)

$hasMutex = $mutex.WaitOne($mutexTimeout)

if (-not $hasMutex) {
return
}

$shouldIntercept = $false

try
{
$interceptFilePath = Join-Path -Path (Join-Path -Path $env:USERPROFILE -ChildPath ".Azure") -ChildPath "InterceptSurvey.json"

if (-not (Test-Path $interceptFilePath)) {
New-Item -ItemType File -Force -Path $interceptFilePath
Init-InterceptFile
} else {
$interceptObject = $null
try {
$fileContent = Get-Content $interceptFilePath | Out-String
$interceptObject = ConvertFrom-Json $fileContent
} catch {
Init-InterceptFile
}

if (-not ($interceptObject -eq $null)) {
$shouldIntercept = Update-InterceptObject($interceptObject)

ConvertTo-Json -InputObject $interceptObject | Out-File $interceptFilePath -Encoding utf8
}
}
} catch {
}

$mutex.ReleaseMutex()

Write-Host "To enable suggestions from Az predictor, run: Set-PSReadLineOption -PredictionSource HistoryAndPlugin"

if ($shouldIntercept) {
$userId = (Get-AzContext).Account.Id
$surveyId = "000000"

if ($userId -ne $null)
{
$surveyId = Get-Random -Maximum 1000000 -SetSeed $userId.GetHashCode()
try {
$azPredictorSettingFilePath = Join-Path -Path (Join-Path -Path $env:USERPROFILE -ChildPath ".Azure") -ChildPath "AzPredictorSettings.json"
$setting = @{
"surveyId"=$surveyId;
}

if (Test-Path $azPredictorSettingFilePath) {
try {
$setting = Get-Content $azPredictorSettingFilePath | Out-String | ConvertFrom-Json
$setting | Add-Member -NotePropertyName "surveyId" -NotePropertyValue $surveyId -Force
} catch {
}
}

ConvertTo-Json -InputObject $setting | Out-File -FilePath $azPredictorSettingFilePath -Encoding utf8
} catch {
}
}

$escape = $([char]27)
Write-Host "`n$escape[7mHow was your experience using Az predictor? $escape[27m`n" -NoNewline; Write-Host "$escape[7mhttp://aka.ms/azpredictorisurvey?SessionId=$surveyId$escape[27m" -NoNewline
Write-Host "`n"
}
16 changes: 16 additions & 0 deletions tools/Az.Tools.Predictor/Az.Tools.Predictor/PromptSurvey.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.internal
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

$targetScript = (Join-Path -Path $PSScriptRoot -ChildPath "InterceptSurvey.ps1")
& $targetScript "Az.Tools.Predictor" 0
24 changes: 23 additions & 1 deletion tools/Az.Tools.Predictor/Az.Tools.Predictor/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,30 @@ sealed class Settings
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};

/// <summary>
/// The maximum number of suggestions that have the same command name.
/// </summary>
public int? MaxAllowedCommandDuplicate { get; set; }
kceiw marked this conversation as resolved.
Show resolved Hide resolved

/// <summary>
/// The service to get the prediction results back.
/// </summary>
public string ServiceUri { get; set; }

/// <summary>
/// Set the user as an internal user.
/// </summary>
public bool? SetAsInternal { get; set; }

/// <summary>
/// The number of suggestions to return to PSReadLine.
/// </summary>
public int? SuggestionCount { get; set; }
public int? MaxAllowedCommandDuplicate { get; set; }

/// <summary>
/// The survey id. It should be internal but make it public so that we can read/write to Json.
/// </summary>
public int? SurveyId { get; set; }

private static bool? _isContinueOnTimeout;
/// <summary>
Expand Down Expand Up @@ -127,6 +141,14 @@ private void OverrideSettingsFromProfile()
{
this.MaxAllowedCommandDuplicate = profileSettings.MaxAllowedCommandDuplicate;
}

this.SetAsInternal = profileSettings.SetAsInternal;
this.SurveyId = profileSettings.SurveyId;

profileSettings.SurveyId = null;

fileContent = JsonSerializer.Serialize<Settings>(profileSettings, new JsonSerializerOptions(Settings._jsonSerializerOptions) { IgnoreNullValues = true });
File.WriteAllText(profileSettingFilePath, fileContent, Encoding.UTF8);
}
catch
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ private IDictionary<string, string> CreateProperties(ITelemetryData telemetryDat
{ "SessionId", telemetryData.SessionId },
{ "CorrelationId", telemetryData.CorrelationId },
{ "UserId", _azContext.UserId },
{ "IsInternal", _azContext.IsInternal.ToString(CultureInfo.InvariantCulture) },
{ "SurveyId", (_azContext as AzContext)?.SurveyId },
{ "HashMacAddress", _azContext.MacAddress },
{ "PowerShellVersion", _azContext.PowerShellVersion.ToString() },
{ "ModuleVersion", _azContext.ModuleVersion.ToString() },
Expand Down