forked from microsoft/PowerShellForGitHub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Telemetry.ps1
483 lines (401 loc) · 17.8 KB
/
Telemetry.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# Singleton. Don't directly access this though....always get it
# by calling Get-BaseTelemetryEvent to ensure that it has been initialized and that you're always
# getting a fresh copy.
$script:GHBaseTelemetryEvent = $null
function Get-PiiSafeString
{
<#
.SYNOPSIS
If PII protection is enabled, returns back an SHA512-hashed value for the specified string,
otherwise returns back the original string, untouched.
.SYNOPSIS
If PII protection is enabled, returns back an SHA512-hashed value for the specified string,
otherwise returns back the original string, untouched.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER PlainText
The plain text that contains PII that may need to be protected.
.EXAMPLE
Get-PiiSafeString -PlainText "Hello World"
Returns back the string "B10A8DB164E0754105B7A99BE72E3FE5" which represents
the SHA512 hash of "Hello World", but only if the "DisablePiiProtection" configuration
value is $false. If it's $true, "Hello World" will be returned.
.OUTPUTS
System.String - A SHA512 hash of PlainText will be returned if the "DisablePiiProtection"
configuration value is $false, otherwise PlainText will be returned untouched.
#>
[CmdletBinding()]
[OutputType([String])]
param(
[Parameter(Mandatory)]
[AllowNull()]
[AllowEmptyString()]
[string] $PlainText
)
if (Get-GitHubConfiguration -Name DisablePiiProtection)
{
return $PlainText
}
else
{
return (Get-SHA512Hash -PlainText $PlainText)
}
}
function Get-BaseTelemetryEvent
{
<#
.SYNOPSIS
Returns back the base object for an Application Insights telemetry event.
.DESCRIPTION
Returns back the base object for an Application Insights telemetry event.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.EXAMPLE
Get-BaseTelemetryEvent
Returns back a base telemetry event, populated with the minimum properties necessary
to correctly report up to this project's telemetry. Callers can then add on to the
event as nececessary.
.OUTPUTS
[PSCustomObject]
#>
[CmdletBinding()]
param()
if ($null -eq $script:GHBaseTelemetryEvent)
{
if (-not (Get-GitHubConfiguration -Name SuppressTelemetryReminder))
{
Write-Log -Message 'Telemetry is currently enabled. It can be disabled by calling "Set-GitHubConfiguration -DisableTelemetry". Refer to USAGE.md#telemetry for more information. Stop seeing this message in the future by calling "Set-GitHubConfiguration -SuppressTelemetryReminder".'
}
$username = Get-PiiSafeString -PlainText $env:USERNAME
$script:GHBaseTelemetryEvent = [PSCustomObject] @{
'name' = 'Microsoft.ApplicationInsights.66d83c523070489b886b09860e05e78a.Event'
'time' = (Get-Date).ToUniversalTime().ToString("O")
'iKey' = (Get-GitHubConfiguration -Name ApplicationInsightsKey)
'tags' = [PSCustomObject] @{
'ai.user.id' = $username
'ai.session.id' = [System.GUID]::NewGuid().ToString()
'ai.application.ver' = $MyInvocation.MyCommand.Module.Version.ToString()
'ai.internal.sdkVersion' = '2.0.1.33027' # The version this schema was based off of.
}
'data' = [PSCustomObject] @{
'baseType' = 'EventData'
'baseData' = [PSCustomObject] @{
'ver' = 2
'properties' = [PSCustomObject] @{
'DayOfWeek' = (Get-Date).DayOfWeek.ToString()
'Username' = $username
}
}
}
}
}
return $script:GHBaseTelemetryEvent.PSObject.Copy() # Get a new instance, not a reference
}
function Invoke-SendTelemetryEvent
{
<#
.SYNOPSIS
Sends an event to Application Insights directly using its REST API.
.DESCRIPTION
Sends an event to Application Insights directly using its REST API.
A very heavy wrapper around Invoke-WebRequest that understands Application Insights and
how to perform its requests with and without console status updates. It also
understands how to parse and handle errors from the REST calls.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER TelemetryEvent
The raw object representing the event data to send to Application Insights.
.OUTPUTS
[PSCustomObject] - The result of the REST operation, in whatever form it comes in.
.NOTES
This mirrors Invoke-GHRestMethod extensively, however the error handling is slightly
different. There wasn't a clear way to refactor the code to make both of these
Invoke-* methods share a common base code. Leaving this as-is to make this file
easier to share out with other PowerShell projects.
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We use global variables sparingly and intentionally for module configuration, and employ a consistent naming convention.")]
param(
[Parameter(Mandatory)]
[PSCustomObject] $TelemetryEvent
)
$jsonConversionDepth = 20 # Seems like it should be more than sufficient
$uri = 'https://dc.services.visualstudio.com/v2/track'
$method = 'POST'
$headers = @{'Content-Type' = 'application/json; charset=UTF-8'}
$body = ConvertTo-Json -InputObject $TelemetryEvent -Depth $jsonConversionDepth -Compress
$bodyAsBytes = [System.Text.Encoding]::UTF8.GetBytes($body)
try
{
Write-Log -Message "Sending telemetry event data to $uri [Timeout = $(Get-GitHubConfiguration -Name WebRequestTimeoutSec))]" -Level Verbose
$params = @{}
$params.Add("Uri", $uri)
$params.Add("Method", $method)
$params.Add("Headers", $headers)
$params.Add("UseDefaultCredentials", $true)
$params.Add("UseBasicParsing", $true)
$params.Add("TimeoutSec", (Get-GitHubConfiguration -Name WebRequestTimeoutSec))
$params.Add("Body", $bodyAsBytes)
# Disable Progress Bar in function scope during Invoke-WebRequest
$ProgressPreference = 'SilentlyContinue'
return Invoke-WebRequest @params
}
catch
{
$ex = $null
$message = $null
$statusCode = $null
$statusDescription = $null
$innerMessage = $null
$rawContent = $null
if ($_.Exception -is [System.Net.WebException])
{
$ex = $_.Exception
$message = $_.Exception.Message
$statusCode = $ex.Response.StatusCode.value__ # Note that value__ is not a typo.
$statusDescription = $ex.Response.StatusDescription
$innerMessage = $_.ErrorDetails.Message
try
{
$rawContent = Get-HttpWebResponseContent -WebResponse $ex.Response
}
catch
{
Write-Log -Message "Unable to retrieve the raw HTTP Web Response:" -Exception $_ -Level Warning
}
}
else
{
Write-Log -Exception $_ -Level Error
throw
}
$output = @()
$output += $message
if (-not [string]::IsNullOrEmpty($statusCode))
{
$output += "$statusCode | $($statusDescription.Trim())"
}
if (-not [string]::IsNullOrEmpty($innerMessage))
{
try
{
$innerMessageJson = ($innerMessage | ConvertFrom-Json)
if ($innerMessageJson -is [String])
{
$output += $innerMessageJson.Trim()
}
elseif (-not [String]::IsNullOrWhiteSpace($innerMessageJson.itemsReceived))
{
$output += "Items Received: $($innerMessageJson.itemsReceived)"
$output += "Items Accepted: $($innerMessageJson.itemsAccepted)"
if ($innerMessageJson.errors.Count -gt 0)
{
$output += "Errors:"
$output += ($innerMessageJson.errors | Format-Table | Out-String)
}
}
else
{
# In this case, it's probably not a normal message from the API
$output += ($innerMessageJson | Out-String)
}
}
catch [System.ArgumentException]
{
# Will be thrown if $innerMessage isn't JSON content
$output += $innerMessage.Trim()
}
}
# It's possible that the API returned JSON content in its error response.
if (-not [String]::IsNullOrWhiteSpace($rawContent))
{
$output += $rawContent
}
$output += "Original body: $body"
$newLineOutput = ($output -join [Environment]::NewLine)
Write-Log -Message $newLineOutput -Level Error
throw $newLineOutput
}
}
function Set-TelemetryEvent
{
<#
.SYNOPSIS
Posts a new telemetry event for this module to the configured Applications Insights instance.
.DESCRIPTION
Posts a new telemetry event for this module to the configured Applications Insights instance.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER EventName
The name of the event that has occurred.
.PARAMETER Properties
A collection of name/value pairs (string/string) that should be associated with this event.
.PARAMETER Metrics
A collection of name/value pair metrics (string/double) that should be associated with
this event.
.EXAMPLE
Set-TelemetryEvent "zFooTest1"
Posts a "zFooTest1" event with the default set of properties and metrics.
.EXAMPLE
Set-TelemetryEvent "zFooTest1" @{"Prop1" = "Value1"}
Posts a "zFooTest1" event with the default set of properties and metrics along with an
additional property named "Prop1" with a value of "Value1".
.NOTES
Because of the short-running nature of this module, we always "flush" the events as soon
as they have been posted to ensure that they make it to Application Insights.
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',
Justification='Function is not state changing')]
param(
[Parameter(Mandatory)]
[string] $EventName,
[hashtable] $Properties = @{},
[hashtable] $Metrics = @{}
)
if (Get-GitHubConfiguration -Name DisableTelemetry)
{
Write-Log -Message "Telemetry has been disabled via configuration. Skipping reporting event [$EventName]." -Level Verbose
return
}
Write-InvocationLog -ExcludeParameter @('Properties', 'Metrics')
try
{
$telemetryEvent = Get-BaseTelemetryEvent
Add-Member -InputObject $telemetryEvent.data.baseData -Name 'name' -Value $EventName -MemberType NoteProperty -Force
# Properties
foreach ($property in $Properties.GetEnumerator())
{
Add-Member -InputObject $telemetryEvent.data.baseData.properties -Name $property.Key -Value $property.Value -MemberType NoteProperty -Force
}
# Measurements
if ($Metrics.Count -gt 0)
{
$measurements = @{}
foreach ($metric in $Metrics.GetEnumerator())
{
$measurements[$metric.Key] = $metric.Value
}
Add-Member -InputObject $telemetryEvent.data.baseData -Name 'measurements' -Value ([PSCustomObject] $measurements) -MemberType NoteProperty -Force
}
$null = Invoke-SendTelemetryEvent -TelemetryEvent $telemetryEvent
}
catch
{
Write-Log -Level Warning -Message @(
"Encountered a problem while trying to record telemetry events.",
"This is non-fatal, but it would be helpful if you could report this problem",
"to the PowerShellForGitHub team for further investigation:"
"",
$_.Exception)
}
}
function Set-TelemetryException
{
<#
.SYNOPSIS
Posts a new telemetry event to the configured Application Insights instance indicating
that an exception occurred in this this module.
.DESCRIPTION
Posts a new telemetry event to the configured Application Insights instance indicating
that an exception occurred in this this module.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER Exception
The exception that just occurred.
.PARAMETER ErrorBucket
A property to be added to the Exception being logged to make it easier to filter to
exceptions resulting from similar scenarios.
.PARAMETER Properties
Additional properties that the caller may wish to be associated with this exception.
.PARAMETER NoFlush
It's not recommended to use this unless the exception is coming from Flush-TelemetryClient.
By default, every time a new exception is logged, the telemetry client will be flushed
to ensure that the event is published to the Application Insights. Use of this switch
prevents that automatic flushing (helpful in the scenario where the exception occurred
when trying to do the actual Flush).
.EXAMPLE
Set-TelemetryException $_
Used within the context of a catch statement, this will post the exception that just
occurred, along with a default set of properties.
.NOTES
Because of the short-running nature of this module, we always "flush" the events as soon
as they have been posted to ensure that they make it to Application Insights.
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',
Justification='Function is not state changing.')]
param(
[Parameter(Mandatory)]
[System.Exception] $Exception,
[string] $ErrorBucket,
[hashtable] $Properties = @{}
)
if (Get-GitHubConfiguration -Name DisableTelemetry)
{
Write-Log -Message "Telemetry has been disabled via configuration. Skipping reporting exception." -Level Verbose
return
}
Write-InvocationLog -ExcludeParameter @('Exception', 'Properties', 'NoFlush')
try
{
$telemetryEvent = Get-BaseTelemetryEvent
$telemetryEvent.data.baseType = 'ExceptionData'
Add-Member -InputObject $telemetryEvent.data.baseData -Name 'handledAt' -Value 'UserCode' -MemberType NoteProperty -Force
# Properties
if (-not [String]::IsNullOrWhiteSpace($ErrorBucket))
{
Add-Member -InputObject $telemetryEvent.data.baseData.properties -Name 'ErrorBucket' -Value $ErrorBucket -MemberType NoteProperty -Force
}
Add-Member -InputObject $telemetryEvent.data.baseData.properties -Name 'Message' -Value $Exception.Message -MemberType NoteProperty -Force
Add-Member -InputObject $telemetryEvent.data.baseData.properties -Name 'HResult' -Value ("0x{0}" -f [Convert]::ToString($Exception.HResult, 16)) -MemberType NoteProperty -Force
foreach ($property in $Properties.GetEnumerator())
{
Add-Member -InputObject $telemetryEvent.data.baseData.properties -Name $property.Key -Value $property.Value -MemberType NoteProperty -Force
}
# Re-create the stack. We'll start with what's in Invocation Info since it's already
# been broken down for us (although it doesn't supply the method name).
$parsedStack = @(
[PSCustomObject] @{
'assembly' = $MyInvocation.MyCommand.Module.Name
'method' = '<unknown>'
'fileName' = $Exception.ErrorRecord.InvocationInfo.ScriptName
'level' = 0
'line' = $Exception.ErrorRecord.InvocationInfo.ScriptLineNumber
}
)
# And then we'll try to parse ErrorRecord's ScriptStackTrace and make this as useful
# as possible.
$stackFrames = $Exception.ErrorRecord.ScriptStackTrace -split [Environment]::NewLine
for ($i = 0; $i -lt $stackFrames.Count; $i++)
{
$frame = $stackFrames[$i]
if ($frame -match '^at (.+), (.+): line (\d+)$')
{
$parsedStack += [PSCustomObject] @{
'assembly' = $MyInvocation.MyCommand.Module.Name
'method' = $Matches[1]
'fileName' = $Matches[2]
'level' = $i + 1
'line' = $Matches[3]
}
}
}
# Finally, we'll build up the Exception data object.
$exceptionData = [PSCustomObject] @{
'id' = (Get-Date).ToFileTime()
'typeName' = $Exception.GetType().FullName
'message' = $Exception.Message
'hasFullStack' = $true
'parsedStack' = $parsedStack
}
Add-Member -InputObject $telemetryEvent.data.baseData -Name 'exceptions' -Value @($exceptionData) -MemberType NoteProperty -Force
$null = Invoke-SendTelemetryEvent -TelemetryEvent $telemetryEvent
}
catch
{
Write-Log -Level Warning -Message @(
"Encountered a problem while trying to record telemetry events.",
"This is non-fatal, but it would be helpful if you could report this problem",
"to the PowerShellForGitHub team for further investigation:",
"",
$_.Exception)
}
}