Skip to content
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
63 changes: 63 additions & 0 deletions src/Common/AzurePSCmdlet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Management.Automation;
using System.Text;
using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;

namespace Microsoft.WindowsAzure.Commands.Utilities.Common
{
Expand Down Expand Up @@ -860,5 +863,65 @@ public virtual bool IsTerminatingError(Exception ex)

return false;
}
//The latest version of Az Wrapper in local. It will be loaded in runtime when the first cmdlet is executed.
//If there is no Az module, the version is "0.0.0"
public static string AzVersion { set; get; }

//Initialized once AzVersion is loadded.
//Format: AzurePowershell/Az0.0.0;%AZUREPS_HOST_ENVIROMENT%
public static string UserAgent { set; get; }

protected string LoadAzVersion()
{
Version defautVersion = new Version("0.0.0");
if (this.Host == null)
{
WriteDebug("Cannot fetch Az version due to no host in current environment");
return defautVersion.ToString();
}

Version latestAz = defautVersion;
string latestSuffix = "";
using (var powershell = System.Management.Automation.PowerShell.Create())
{
try
{
powershell.Runspace = RunspaceFactory.CreateRunspace(this.Host);
powershell.AddCommand("Get-Module");
powershell.AddParameter("Name", "Az");
powershell.AddParameter("ListAvailable", true);
powershell.Runspace.Open();
Collection<PSObject> outputs = powershell.Invoke();
foreach (PSObject obj in outputs)
{
string psVersion = obj.Properties["Version"].Value.ToString();
int pos = psVersion.IndexOf('-');
string currentSuffix = (pos == -1 || pos == psVersion.Length - 1) ? "" : psVersion.Substring(pos + 1);
Version currentAz = (pos == -1) ? new Version(psVersion) : new Version(psVersion.Substring(0, pos));
if (currentAz > latestAz)
{
latestAz = currentAz;
latestSuffix = currentSuffix;
}
else if (currentAz == latestAz)
{
latestSuffix = String.Compare(latestSuffix, currentSuffix) > 0 ? latestSuffix : currentSuffix;
}
}
}
catch (Exception e)
{
WriteDebug(string.Format("Cannot fetch Az version due to exception: {0}", e.Message));
return defautVersion.ToString();
}
}
string ret = latestAz.ToString();
if (!String.IsNullOrEmpty(latestSuffix))
{
ret += "-" + latestSuffix;
}
WriteDebug(string.Format("Sought all Az modules and got latest version {0}", ret));
return ret;
}
}
}
27 changes: 22 additions & 5 deletions src/Common/MetricHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Management.Automation.Host;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;

Expand Down Expand Up @@ -272,12 +273,17 @@ private void PopulatePropertiesFromQos(AzurePSQoSEvent qos, IDictionary<string,
eventProperties.Add("CommandParameters", qos.Parameters);
eventProperties.Add("UserId", qos.Uid);
eventProperties.Add("x-ms-client-request-id", qos.ClientRequestId);
eventProperties.Add("UserAgent", AzurePowerShell.UserAgentValue.ToString());
eventProperties.Add("UserAgent", qos.UserAgent);
eventProperties.Add("HashMacAddress", HashMacAddress);
eventProperties.Add("PowerShellVersion", PSVersion);
eventProperties.Add("Version", AzurePowerShell.AssemblyVersion);
eventProperties.Add("Version", qos.AzVersion);
eventProperties.Add("CommandParameterSetName", qos.ParameterSetName);
eventProperties.Add("CommandInvocationName", qos.InvocationName);
eventProperties.Add("start-time", qos.StartTime.ToUniversalTime().ToString("o"));
eventProperties.Add("end-time", qos.EndTime.ToUniversalTime().ToString("o"));
eventProperties.Add("duration", qos.Duration.ToString("c"));
eventProperties.Add("subscription-id", qos.SubscriptionId);
eventProperties.Add("tenant-id", qos.TenantId);

if (qos.InputFromPipeline != null)
{
Expand Down Expand Up @@ -371,19 +377,25 @@ public class AzurePSQoSEvent
private readonly Stopwatch _timer;

public DateTimeOffset StartTime { get; set; }
public DateTimeOffset EndTime { get; set; }
public TimeSpan Duration { get; set; }
public bool IsSuccess { get; set; }
public string CommandName { get; set; }
public string ModuleName { get; set; }
public string ModuleVersion { get; set; }
public string HostVersion { get; set; }
public string AzVersion { get; set; }
public string UserAgent { get; set; }
public string Parameters { get; set; }
public bool? InputFromPipeline { get; set; }
public bool? OutputToPipeline { get; set; }
public Exception Exception { get; set; }
public string Uid { get; set; }
public string ClientRequestId { get; set; }
public string SessionId { get; set; }
public string SubscriptionId { get; set; }
public string TenantId { get; set; }

public string ParameterSetName { get; set; }
public string InvocationName { get; set; }
public Dictionary<string, string> CustomProperties { get; private set; }
Expand All @@ -410,12 +422,17 @@ public void FinishQosEvent()
{
_timer.Stop();
Duration = _timer.Elapsed;
EndTime = DateTimeOffset.Now;
}

public override string ToString()
{
return string.Format(
"AzureQoSEvent: CommandName - {0}; IsSuccess - {1}; Duration - {2}; Exception - {3};",
CommandName, IsSuccess, Duration, Exception);
string ret = string.Format(
"AzureQoSEvent: CommandName - {0}; IsSuccess - {1}; Duration - {2};", CommandName, IsSuccess, Duration);
if (Exception != null)
{
ret = $"{ret}; Exception - {Exception};";
}
return ret;
}
}
42 changes: 23 additions & 19 deletions src/ResourceManager/Version2016_09_01/AzureRMCmdlet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Net.Http.Headers;
using System.Security.Authentication;
using System.Text;

Expand Down Expand Up @@ -172,7 +173,7 @@ protected override string DataCollectionWarning
/// Whether this cmdlet requires default context.
/// If false, the logic of referencing default context would be omitted.
/// </summary>
protected virtual bool RequireDefaultContext => true;
protected virtual bool RequireDefaultContext() { return true; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've already been using this property in two cmdlets. Changing it to a method will require us to change those cmdlets as well. Would you want me to do that?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For example here we need to do the following update

-        protected override bool RequireDefaultContext => false;
+        protected override bool RequireDefaultContext() { return false; }

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes. your original approach doesn't work. You can test too. No idea the syntax you are using. but my approach is the safe way and I verified it. I haven't submitted my commits in azure-powershell.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I write a simple example. It shows your code is correct. I'd like to change them back to follow convention if there is no other problem.


/// <summary>
/// Return a default context safely if it is available, without throwing if it is not setup
Expand Down Expand Up @@ -307,6 +308,17 @@ protected override void InitializeQosEvent()
ParameterSetName = this.ParameterSetName
};

if (AzVersion == null)
{
AzVersion = this.LoadAzVersion();
UserAgent = new ProductInfoHeaderValue("AzurePowershell", string.Format("Az{0}", AzVersion)).ToString();
string HostEnv = Environment.GetEnvironmentVariable("AZUREPS_HOST_ENVIRONMENT");
if (!String.IsNullOrWhiteSpace(HostEnv))
UserAgent += string.Format(";{0}", HostEnv.Trim());
}
_qosEvent.AzVersion = AzVersion;
_qosEvent.UserAgent = UserAgent;

if (this.MyInvocation != null && !string.IsNullOrWhiteSpace(this.MyInvocation.InvocationName))
{
_qosEvent.InvocationName = this.MyInvocation.InvocationName;
Expand All @@ -321,24 +333,23 @@ protected override void InitializeQosEvent()
}

IAzureContext context;
if (RequireDefaultContext
&& TryGetDefaultContext(out context)
&& context.Account != null
&& !string.IsNullOrWhiteSpace(context.Account.Id))
_qosEvent.Uid = "defaultid";
if (RequireDefaultContext() && TryGetDefaultContext(out context))
{
_qosEvent.Uid = MetricHelper.GenerateSha256HashString(context.Account.Id.ToString());
}
else
{
_qosEvent.Uid = "defaultid";
_qosEvent.SubscriptionId = context.Subscription?.Id;
_qosEvent.TenantId = context.Tenant?.Id;
if(context.Account != null && !String.IsNullOrWhiteSpace(context.Account.Id))
{
_qosEvent.Uid = MetricHelper.GenerateSha256HashString(context.Account.Id.ToString());
}
}
}

protected override void LogCmdletStartInvocationInfo()
{
base.LogCmdletStartInvocationInfo();
IAzureContext context;
if (RequireDefaultContext
if (RequireDefaultContext()
&& TryGetDefaultContext(out context)
&& context.Account != null
&& context.Account.Id != null)
Expand All @@ -348,13 +359,6 @@ protected override void LogCmdletStartInvocationInfo()
}
}

protected override void LogCmdletEndInvocationInfo()
{
base.LogCmdletEndInvocationInfo();
string message = string.Format("{0} end processing.", this.GetType().Name);
WriteDebugWithTimestamp(message);
}

protected override void SetupDebuggingTraces()
{
ServiceClientTracing.IsEnabled = true;
Expand Down Expand Up @@ -387,7 +391,7 @@ protected override void BeginProcessing()
InitializeEventHandlers();
AzureSession.Instance.ClientFactory.RemoveHandler(typeof(RPRegistrationDelegatingHandler));
IAzureContext context;
if (RequireDefaultContext
if (RequireDefaultContext()
&& TryGetDefaultContext(out context)
&& context.Account != null
&& context.Subscription != null)
Expand Down