Framework/Helpers/AIOrgTelemetryHelper.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
Set-StrictMode -Version Latest

class AIOrgTelemetryHelper {
    static hidden [string[]] $ParamsToMask = @("OMSSharedKey");
    static hidden [Microsoft.ApplicationInsights.TelemetryClient] $OrgTelemetryClient;
    static hidden [Microsoft.ApplicationInsights.TelemetryClient] $UsageTelemetryClient;
    static [PSObject] $CommonProperties;
    static AIOrgTelemetryHelper() {
        [AIOrgTelemetryHelper]::OrgTelemetryClient = [Microsoft.ApplicationInsights.TelemetryClient]::new()
    }

    static [void] TrackEvent([string] $Name) {
        [AIOrgTelemetryHelper]::TrackEvent($Name, $null, $null);
    }

    static [void] TrackEventWithOnlyProperties([string] $Name, [hashtable] $Properties) {
        [AIOrgTelemetryHelper]::TrackEvent($Name, $Properties, $null);
    }

    static [void] TrackEventWithOnlyMetrics([string] $Name, [hashtable] $Metrics) {
        [AIOrgTelemetryHelper]::TrackEvent($Name, $null, $Metrics);
    }

    static [void] TrackEvent([string] $Name, [hashtable] $Properties, [hashtable] $Metrics) {
        if (![RemoteReportHelper]::IsAIOrgTelemetryEnabled()) { return; };
        [AIOrgTelemetryHelper]::TrackEventInternal($Name, $Properties, $Metrics);
        [AIOrgTelemetryHelper]::OrgTelemetryClient.Flush();
    }

    static [void] TrackEvents([System.Collections.ArrayList] $events) {
        if (![RemoteReportHelper]::IsAIOrgTelemetryEnabled()) { return; };
        foreach ($item in $events) {
            [AIOrgTelemetryHelper]::TrackEventInternal($item.Name, $item.Properties, $item.Metrics);
        }
        [AIOrgTelemetryHelper]::OrgTelemetryClient.Flush();
    }

    static [void] TrackCommandExecution([string] $Name, [hashtable] $Properties, [hashtable] $Metrics, [System.Management.Automation.InvocationInfo] $invocationContext) {
        if (![RemoteReportHelper]::IsAIOrgTelemetryEnabled()) { return; };
        $Properties = [AIOrgTelemetryHelper]::AttachInvocationInfo($Properties, $invocationContext);
        [AIOrgTelemetryHelper]::TrackEventInternal($Name, $Properties, $Metrics);
        [AIOrgTelemetryHelper]::OrgTelemetryClient.Flush();
    }

    static [void] TrackException([System.Management.Automation.ErrorRecord] $ErrorRecord, [System.Management.Automation.InvocationInfo] $InvocationContext) {
        [AIOrgTelemetryHelper]::TrackException($ErrorRecord, $null, $null, $InvocationContext);
    }

    static [void] TrackExceptionWithOnlyProperties([System.Management.Automation.ErrorRecord] $ErrorRecord, [hashtable] $Properties, [System.Management.Automation.InvocationInfo] $InvocationContext) {
        [AIOrgTelemetryHelper]::TrackException($ErrorRecord, $Properties, $null, $InvocationContext);
    }

    static [void] TrackExceptionWithOnlyMetrics([System.Management.Automation.ErrorRecord] $ErrorRecord, [hashtable] $Metrics, [System.Management.Automation.InvocationInfo] $InvocationContext) {
        [AIOrgTelemetryHelper]::TrackException($ErrorRecord, $null, $Metrics, $InvocationContext);
    }

    static [void] TrackException([System.Management.Automation.ErrorRecord] $ErrorRecord, [hashtable] $Properties, [hashtable] $Metrics, [System.Management.Automation.InvocationInfo] $InvocationContext) {
        try {
            if (![RemoteReportHelper]::IsAIOrgTelemetryEnabled()) { return; };
            $Properties = [AIOrgTelemetryHelper]::AttachInvocationInfo($Properties, $InvocationContext);
            $Properties = [AIOrgTelemetryHelper]::AttachCommonProperties($Properties);
            $Metrics = [AIOrgTelemetryHelper]::AttachCommonMetrics($Metrics);
            $ex = [Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry]::new()
            $ex.Exception = $ErrorRecord.Exception
            try{
                $ex.Properties.Add("ScriptStackTrace", $ErrorRecord.ScriptStackTrace)
            }catch{}
            $Properties.Keys | ForEach-Object {
                try{
                    $ex.Properties.Add($_, $Properties[$_].ToString());
                }
                catch{
                }
            }
            $Metrics.Keys | ForEach-Object {
                try{
                    $ex.Metrics.Add($_, $Metrics[$_]);
                }
                catch{
                }
            }
            [AIOrgTelemetryHelper]::OrgTelemetryClient.InstrumentationKey = [RemoteReportHelper]::GetAIOrgTelemetryKey();
            [AIOrgTelemetryHelper]::OrgTelemetryClient.TrackException($ex);
            [AIOrgTelemetryHelper]::OrgTelemetryClient.Flush();
        }
        catch {
        }
    }


    hidden static [void] TrackEventInternal([string] $Name, [hashtable] $Properties, [hashtable] $Metrics) {
        $Properties = [AIOrgTelemetryHelper]::AttachCommonProperties($Properties);
        $Metrics = [AIOrgTelemetryHelper]::AttachCommonMetrics($Metrics);
        try {
            $event = [Microsoft.ApplicationInsights.DataContracts.EventTelemetry]::new()
            $event.Name = $Name
            $Properties.Keys | ForEach-Object {
                try {
                    $event.Properties.Add($_, ($Properties[$_].ToString()));
                }
                catch {
                }
            }
            $Metrics.Keys | ForEach-Object {
                try {
                    $event.Metrics.Add($_, $Metrics[$_]);
                }
                catch {
                }
            }
            [AIOrgTelemetryHelper]::OrgTelemetryClient.InstrumentationKey = [RemoteReportHelper]::GetAIOrgTelemetryKey();
            [AIOrgTelemetryHelper]::OrgTelemetryClient.TrackEvent($event);
        }
        catch {
        }
    }

    hidden static [hashtable] AttachCommonProperties([hashtable] $Properties) {
        if ($Properties -eq $null) {
            $Properties = @{}
        }
        else {
            $Properties = $Properties.Clone()
        }
        try {
            $NA = "NA";
            try {
                $Properties.Add("ScanSource", [RemoteReportHelper]::GetScanSource());
            }
            catch {}
            try {
                $module = Get-Module 'AzSK*' | Select-Object -First 1
                $Properties.Add("ScannerModuleName", $module.Name);
                $Properties.Add("ScannerVersion", $module.Version.ToString());
            }
            catch {}
            try {
                $azureContext = Get-AzureRmContext
                try {
                    $Properties.Add([TelemetryKeys]::SubscriptionId, $azureContext.Subscription.Id)
                }
                catch {}
                try {
                    $Properties.Add([TelemetryKeys]::SubscriptionName, $azureContext.Subscription.Name)
                }
                catch {}
                try {
                    $Properties.Add("AzureEnv", $azureContext.Environment.Name)
                }
                catch {}
                try {
                    $Properties.Add("TenantId", $azureContext.Tenant.Id)
                }
                catch {}
                try {
                    $Properties.Add("AccountId", $azureContext.Account.Id)
                }
                catch {}
                try {
                    if ($Properties.ContainsKey("RunIdentifier")) {
                        $actualRunId = $Properties["RunIdentifier"]
                        $Properties["UniqueRunIdentifier"] = [RemoteReportHelper]::Mask($azureContext.Account.Id + '##' + $actualRunId.ToString())
                    }
                }
                catch {}
                try {
                    $Properties.Add("AccountType", $azureContext.Account.Type);
                }
                catch {}
            }
            catch {
            }
        }
        catch {
        }
        return $Properties;
    }

    hidden static [hashtable] AttachCommonMetrics([hashtable] $Metrics) {
        if ($Metrics -eq $null) {
            $Metrics = @{}
        }
        else {
            $Metrics = $Metrics.Clone()
        }
        return $Metrics;
    }

    hidden static [hashtable] AttachInvocationInfo([hashtable] $Properties, [System.Management.Automation.InvocationInfo] $invocationContext) {
        if ($Properties -eq $null) {
            $Properties = @{}
        }
        else {
            $Properties = $Properties.Clone()
        }
        if ($invocationContext -eq $null) { return $Properties};
        $Properties.Add("Command", $invocationContext.MyCommand.Name)
        $params = @{}
        $invocationContext.BoundParameters.Keys | ForEach-Object {
            $value = "MASKED"
            if (![AIOrgTelemetryHelper]::ParamsToMask.Contains($_)) {
                $value = $invocationContext.BoundParameters[$_].ToString()
            }
            $Properties.Add("Param" + $_, $value)
            $params.Add("$_", $value)
        }
        $Properties.Add("Params", [Helpers]::ConvertToJsonCustomCompressed($params))
        $loadedModules = Get-Module | % { $_.Name + "=" + $_.Version.ToString()}
        $Properties.Add("LoadedModules" , ($loadedModules -join ';'))
        return $Properties;
    }

    static [void] PublishEvent([string] $EventName, [hashtable] $Properties, [hashtable] $Metrics) {
        try {
            #return if telemetry key is empty
            $telemetryKey= [RemoteReportHelper]::GetAIOrgTelemetryKey()
            if ([string]::IsNullOrWhiteSpace($telemetryKey)) { return; };
            $eventObj = [AIOrgTelemetryHelper]::GetEventBaseObject($EventName)
            $eventObj=[AIOrgTelemetryHelper]::SetCommonProperties($eventObj)

            if ($Properties -ne $null) {
                $Properties.Keys | ForEach-Object {
                    try {
                        if (!$eventObj.data.baseData.properties.ContainsKey($_)) {
                            $eventObj.data.baseData.properties.Add($_ , $Properties[$_].ToString())
                        }
                    }
                    catch
                    {#left blank intentionally
                    }
                }
            }
            if ($Metrics -ne $null) {
                $Metrics.Keys | ForEach-Object {
                    try {
                        $metric = $Metrics[$_] -as [double]
                        if (!$eventObj.data.baseData.measurements.ContainsKey($_) -and $metric -ne $null) {
                            $eventObj.data.baseData.measurements.Add($_ , $Metrics[$_])
                        }
                    }
                    catch {#left blank intentionally
                    }
                }
            }

            $eventJson = ConvertTo-Json $eventObj -Depth 100 -Compress

            Invoke-WebRequest -Uri "https://dc.services.visualstudio.com/v2/track" `
                -Method Post `
                -ContentType "application/x-json-stream" `
                -Body $eventJson `
                -UseBasicParsing | Out-Null
        }
        catch {#left blank intentionally
        }
    }

    static [PSObject] GetEventBaseObject([string] $EventName) {
    $telemetryKey= [RemoteReportHelper]::GetAIOrgTelemetryKey()
    $eventObj = "" | Select-Object data, iKey, name, tags, time
    $eventObj.iKey = $telemetryKey
    $eventObj.name = "Microsoft.ApplicationInsights." + $telemetryKey.Replace("-", "") + ".Event"
    $eventObj.time = [datetime]::UtcNow.ToString("o")

    $eventObj.tags = "" | Select-Object ai.internal.sdkVersion
    $eventObj.tags.'ai.internal.sdkVersion' = "dotnet: 2.1.0.26048"

    $eventObj.data = "" | Select-Object baseData, baseType
    $eventObj.data.baseType = "EventData"
    $eventObj.data.baseData = "" | Select-Object ver, name, measurements, properties

    $eventObj.data.baseData.ver = 2
    $eventObj.data.baseData.name = $EventName

    $eventObj.data.baseData.measurements = New-Object 'system.collections.generic.dictionary[string,double]'
    $eventObj.data.baseData.properties = New-Object 'system.collections.generic.dictionary[string,string]'

    return $eventObj;
    }

    #Telemetry functions -- start here
  static [PSObject]  SetCommonProperties([psobject] $EventObj) {
    $notAvailable = "NA"
    if([AIOrgTelemetryHelper]::CommonProperties)
     {    
        try{
        $EventObj.data.baseData.properties.Add("SubscriptionId",[AIOrgTelemetryHelper]::CommonProperties.SubscriptionId)
        $EventObj.data.baseData.properties.Add("SubscriptionName",[AIOrgTelemetryHelper]::CommonProperties.SubscriptionName)        
        $azureContext = Get-AzureRmContext
        $EventObj.data.baseData.properties.Add("TenantId", $azureContext.Tenant.Id)
        $EventObj.data.baseData.properties.Add("AccountId", $azureContext.Account.Id)
        }
        catch{
            #Intentionally kept blank to avoid any break in event push
        }
     }
      return $EventObj
}
}