-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathTrace2.cs
More file actions
676 lines (610 loc) · 21.7 KB
/
Copy pathTrace2.cs
File metadata and controls
676 lines (610 loc) · 21.7 KB
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading;
namespace GitCredentialManager;
/// <summary>
/// The different event types tracked in the TRACE2 tracing
/// system.
/// </summary>
public enum Trace2Event
{
[JsonStringEnumMemberName("version")]
Version = 0,
[JsonStringEnumMemberName("start")]
Start = 1,
[JsonStringEnumMemberName("exit")]
Exit = 2,
[JsonStringEnumMemberName("child_start")]
ChildStart = 3,
[JsonStringEnumMemberName("child_exit")]
ChildExit = 4,
[JsonStringEnumMemberName("error")]
Error = 5,
[JsonStringEnumMemberName("region_enter")]
RegionEnter = 6,
[JsonStringEnumMemberName("region_leave")]
RegionLeave = 7,
}
/// <summary>
/// Classifications of processes invoked by GCM.
/// </summary>
public enum Trace2ProcessClass
{
[JsonStringEnumMemberName("none")]
None = 0,
[JsonStringEnumMemberName("ui_helper")]
UIHelper = 1,
[JsonStringEnumMemberName("git")]
Git = 2,
[JsonStringEnumMemberName("other")]
Other = 3
}
/// <summary>
/// Stores various TRACE2 format targets user has enabled.
/// Check <see cref="Trace2FormatTarget"/> for supported formats.
/// </summary>
public class Trace2Settings
{
public IDictionary<Trace2FormatTarget, string> FormatTargetsAndValues { get; set; } =
new Dictionary<Trace2FormatTarget, string>();
}
/// <summary>
/// Specifies a "text span" (i.e. space between two pipes) for the performance format target.
/// </summary>
public class PerformanceFormatSpan
{
public int Size { get; set; }
public int BeginPadding { get; set; }
public int EndPadding { get; set; }
}
/// <summary>
/// Class that manages regions.
/// </summary>
public class Region : DisposableObject
{
private readonly ITrace2 _trace2;
private readonly string _category;
private readonly string _label;
private readonly string _filePath;
private readonly int _lineNumber;
private readonly string _message;
private readonly DateTimeOffset _startTime;
public Region(ITrace2 trace2, string category, string label, string filePath, int lineNumber, string message = "")
{
_trace2 = trace2;
_category = category;
_label = label;
_filePath = filePath;
_lineNumber = lineNumber;
_message = message;
_startTime = DateTimeOffset.UtcNow;
_trace2.WriteRegionEnter(_category, _label, _message, _filePath, _lineNumber);
}
protected override void ReleaseManagedResources()
{
double relativeTime = (DateTimeOffset.UtcNow - _startTime).TotalSeconds;
_trace2.WriteRegionLeave(relativeTime, _category, _label, _message, _filePath, _lineNumber);
}
}
/// <summary>
/// Represents the application's TRACE2 tracing system.
/// </summary>
public interface ITrace2 : IDisposable
{
/// <summary>
/// Initialize TRACE2 tracing by initializing multi-use fields and setting up any configured target formats.
/// </summary>
/// <param name="startTime">Approximate time calling application began executing.</param>
void Initialize(DateTimeOffset startTime);
/// <summary>
/// Write Version and Start events.
/// </summary>
/// <param name="appPath">The path to the application.</param>
/// <param name="args">Args passed to the application (if applicable).</param>
/// <param name="filePath">Path of the file this method is called from.</param>
/// <param name="lineNumber">Line number of file this method is called from.</param>
void Start(string appPath,
string[] args,
[System.Runtime.CompilerServices.CallerFilePath] string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int lineNumber = 0);
/// <summary>
/// Write Exit event and dispose of writers.
/// </summary>
/// <param name="exitCode">The exit code of the GCM application.</param>
/// <param name="filePath">Path of the file this method is called from.</param>
/// <param name="lineNumber">Line number of file this method is called from.</param>
void Stop(int exitCode,
[System.Runtime.CompilerServices.CallerFilePath] string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int lineNumber = 0);
/// <summary>
/// Writes information related to startup of child process to trace writer.
/// </summary>
/// <param name="startTime">Time at which child process began executing.</param>
/// <param name="processClass">Process classification.</param>
/// <param name="useShell">Specifies whether or not OS shell was used to start the process.</param>
/// <param name="appName">Name of application running in child process.</param>
/// <param name="argv">Arguments specific to the child process.</param>
/// <param name="sid">The child process's session id.</param>
/// <param name="filePath">Path of the file this method is called from.</param>
/// <param name="lineNumber">Line number of file this method is called from.</param>
void WriteChildStart(DateTimeOffset startTime,
Trace2ProcessClass processClass,
bool useShell,
string appName,
string argv,
[System.Runtime.CompilerServices.CallerFilePath]
string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber]
int lineNumber = 0);
/// <summary>
/// Writes information related to exit of child process to trace writer.
/// </summary>
/// <param name="relativeTime">Runtime of child process.</param>
/// <param name="pid">Id of exiting process.</param>
/// <param name="code">Process exit code.</param>
/// <param name="filePath">Path of the file this method is called from.</param>
/// <param name="lineNumber">Line number of file this method is called from.</param>
void WriteChildExit(
double relativeTime,
int pid,
int code,
[System.Runtime.CompilerServices.CallerFilePath]
string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber]
int lineNumber = 0);
/// <summary>
/// Writes an error as a message to the trace writer.
/// </summary>
/// <param name="errorMessage">The error message to write.</param>
/// <param name="parameterizedMessage">The error format string.</param>
/// <param name="filePath">Path of the file this method is called from.</param>
/// <param name="lineNumber">Line number of file this method is called from.</param>
void WriteError(
string errorMessage,
string parameterizedMessage = null,
[System.Runtime.CompilerServices.CallerFilePath]
string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber]
int lineNumber = 0);
/// <summary>
/// Creates a region and manages entry/leaving.
/// </summary>
/// <param name="category">Category of region.</param>
/// <param name="label">Description of region.</param>
/// <param name="message">Message associated with entering region.</param>
/// <param name="filePath">Path of the file this method is called from.</param>
/// <param name="lineNumber">Line number of file this method is called from.</param>
Region CreateRegion(
string category,
string label,
string message = "",
[System.Runtime.CompilerServices.CallerFilePath]
string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber]
int lineNumber = 0);
/// <summary>
/// Writes a region enter message to the trace writer.
/// </summary>
/// <param name="category">Category of region.</param>
/// <param name="label">Description of region.</param>
/// <param name="message">Message associated with entering region.</param>
/// <param name="filePath">Path of the file this method is called from.</param>
/// <param name="lineNumber">Line number of file this method is called from.</param>
void WriteRegionEnter(
string category,
string label,
string message = "",
[System.Runtime.CompilerServices.CallerFilePath]
string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber]
int lineNumber = 0);
/// <summary>
/// Writes a region leave message to the trace writer.
/// </summary>
/// <param name="relativeTime">Time of region execution.</param>
/// <param name="category">Category of region.</param>
/// <param name="label">Description of region.</param>
/// <param name="message">Message associated with entering region.</param>
/// <param name="filePath">Path of the file this method is called from.</param>
/// <param name="lineNumber">Line number of file this method is called from.</param>
void WriteRegionLeave(
double relativeTime,
string category,
string label,
string message = "",
[System.Runtime.CompilerServices.CallerFilePath]
string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber]
int lineNumber = 0);
}
public class Trace2 : DisposableObject, ITrace2
{
private readonly ICommandContext _commandContext;
private readonly object _writersLock = new object();
private readonly Encoding _utf8NoBomEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
private readonly List<ITrace2Writer> _writers = new List<ITrace2Writer>();
private const string GitSidVariable = "GIT_TRACE2_PARENT_SID";
private DateTimeOffset _applicationStartTime;
private Trace2Settings _settings;
private string _sid;
private bool _initialized;
// Increment with each new child process that is tracked
private int _childProcCounter = 0;
public Trace2(ICommandContext commandContext)
{
_commandContext = commandContext;
}
public void Initialize(DateTimeOffset startTime)
{
if (_initialized)
{
return;
}
_applicationStartTime = startTime;
_settings = _commandContext.Settings.GetTrace2Settings();
_sid = ProcessManager.Sid;
InitializeWriters();
_initialized = true;
}
public void Start(string appPath,
string[] args,
string filePath,
int lineNumber)
{
if (!AssemblyUtils.TryGetAssemblyVersion(out string version))
{
// A version is required for TRACE2, so if this call fails
// manually set the version.
version = "0.0.0";
}
WriteVersion(version, filePath, lineNumber);
WriteStart(appPath, args, filePath, lineNumber);
}
public void Stop(int exitCode, string filePath, int lineNumber)
{
WriteExit(exitCode, filePath, lineNumber);
}
public void WriteChildStart(DateTimeOffset startTime,
Trace2ProcessClass processClass,
bool useShell,
string appName,
string argv,
string filePath = "",
int lineNumber = 0)
{
// Some child processes are started before TRACE2 can be initialized.
// Since certain dependencies are not available until initialization,
// we must immediately return if this method is invoked prior to
// initialization.
if (!_initialized)
{
return;
}
// Always add name of the application the process is executing
var procArgs = new List<string>()
{
Path.GetFileName(appName)
};
// If the process has arguments, append them.
if (!string.IsNullOrEmpty(argv))
{
procArgs.AddRange(argv.Split(' '));
}
WriteMessage(new ChildStartMessage()
{
Event = Trace2Event.ChildStart,
Sid = _sid,
Time = startTime,
Thread = BuildThreadName(),
File = Path.GetFileName(filePath),
Line = lineNumber,
Id = ++_childProcCounter,
Classification = processClass,
UseShell = useShell,
Argv = procArgs,
ElapsedTime = (DateTimeOffset.UtcNow - _applicationStartTime).TotalSeconds,
Depth = ProcessManager.Depth,
});
}
public void WriteChildExit(
double relativeTime,
int pid,
int code,
string filePath = "",
int lineNumber = 0)
{
// Some child processes are started before TRACE2 can be initialized.
// Since certain dependencies are not available until initialization,
// we must immediately return if this method is invoked prior to
// initialization.
if (!_initialized)
{
return;
}
WriteMessage(new ChildExitMessage()
{
Event = Trace2Event.ChildExit,
Sid = _sid,
Time = DateTimeOffset.UtcNow,
Thread = BuildThreadName(),
File = Path.GetFileName(filePath),
Line = lineNumber,
Id = _childProcCounter,
Pid = pid,
Code = code,
ElapsedTime = (DateTimeOffset.UtcNow - _applicationStartTime).TotalSeconds,
RelativeTime = relativeTime,
Depth = ProcessManager.Depth
});
}
public void WriteError(
string errorMessage,
string parameterizedMessage = null,
[System.Runtime.CompilerServices.CallerFilePath] string filePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int lineNumber = 0)
{
// It is possible for an error to be thrown before TRACE2 can be initialized.
// Since certain dependencies are not available until initialization,
// we must immediately return if this method is invoked prior to
// initialization.
if (!_initialized)
{
return;
}
WriteMessage(new ErrorMessage()
{
Event = Trace2Event.Error,
Sid = _sid,
Time = DateTimeOffset.UtcNow,
Thread = BuildThreadName(),
File = Path.GetFileName(filePath),
Line = lineNumber,
Message = errorMessage,
ParameterizedMessage = parameterizedMessage ?? errorMessage,
Depth = ProcessManager.Depth
});
}
public Region CreateRegion(
string category,
string label,
string message,
string filePath,
int lineNumber)
{
return new Region(this, category, label, filePath, lineNumber, message);
}
public void WriteRegionEnter(
string category,
string label,
string message = "",
string filePath = "",
int lineNumber = 0)
{
WriteMessage(new RegionEnterMessage()
{
Event = Trace2Event.RegionEnter,
Sid = _sid,
Time = DateTimeOffset.UtcNow,
Category = category,
Label = label,
Message = message == "" ? label : message,
Thread = BuildThreadName(),
File = Path.GetFileName(filePath),
Line = lineNumber,
ElapsedTime = (DateTimeOffset.UtcNow - _applicationStartTime).TotalSeconds,
Depth = ProcessManager.Depth
});
}
public void WriteRegionLeave(
double relativeTime,
string category,
string label,
string message = "",
string filePath = "",
int lineNumber = 0)
{
WriteMessage(new RegionLeaveMessage()
{
Event = Trace2Event.RegionLeave,
Sid = _sid,
Time = DateTimeOffset.UtcNow,
Category = category,
Label = label,
Message = message == "" ? label : message,
Thread = BuildThreadName(),
File = Path.GetFileName(filePath),
Line = lineNumber,
ElapsedTime = (DateTimeOffset.UtcNow - _applicationStartTime).TotalSeconds,
RelativeTime = relativeTime,
Depth = ProcessManager.Depth
});
}
protected override void ReleaseManagedResources()
{
lock (_writersLock)
{
try
{
for (int i = _writers.Count - 1; i >= 0; i--)
{
using (_writers[i])
{
_writers.RemoveAt(i);
}
}
}
catch
{
/* squelch */
}
}
base.ReleaseManagedResources();
}
internal static bool TryGetPipeName(string eventTarget, out string name)
{
// Use prefixes to determine whether target is a named pipe/socket
if (eventTarget.StartsWith("af_unix:", StringComparison.OrdinalIgnoreCase) ||
eventTarget.StartsWith(@"\\.\pipe\", StringComparison.OrdinalIgnoreCase) ||
eventTarget.StartsWith("//./pipe/", StringComparison.OrdinalIgnoreCase))
{
name = PlatformUtils.IsWindows()
? eventTarget.Replace('/', '\\')
.TrimUntilIndexOf(@"\\.\pipe\")
: eventTarget.Replace("af_unix:dgram:", "")
.Replace("af_unix:stream:", "")
.Replace("af_unix:", "");
return true;
}
name = "";
return false;
}
private void InitializeWriters()
{
// Set up the correct writer for every enabled format target.
foreach (var formatTarget in _settings.FormatTargetsAndValues)
{
if (TryGetPipeName(formatTarget.Value, out string name)) // Write to named pipe/socket
{
AddWriter(new Trace2CollectorWriter(formatTarget.Key, (
() => new NamedPipeClientStream(".", name,
PipeDirection.Out,
PipeOptions.Asynchronous)
)
));
}
else if (formatTarget.Value.IsTruthy()) // Write to stderr
{
AddWriter(new Trace2StreamWriter(formatTarget.Key, _commandContext.Streams.Error));
}
else if (Path.IsPathRooted(formatTarget.Value)) // Write to file
{
try
{
AddWriter(new Trace2FileWriter(formatTarget.Key, formatTarget.Value));
}
catch (Exception ex)
{
Console.Error.WriteLine($"warning: unable to trace to file '{formatTarget.Value}': {ex.Message}");
}
}
}
}
private void WriteVersion(
string gcmVersion,
string filePath,
int lineNumber,
string eventFormatVersion = "3")
{
EnsureArgument.NotNull(gcmVersion, nameof(gcmVersion));
WriteMessage(new VersionMessage()
{
Event = Trace2Event.Version,
Sid = _sid,
Time = DateTimeOffset.UtcNow,
Thread = BuildThreadName(),
File = Path.GetFileName(filePath),
Line = lineNumber,
Evt = eventFormatVersion,
Exe = gcmVersion
});
}
private void WriteStart(
string appPath,
string[] args,
string filePath,
int lineNumber)
{
// Prepend GCM exe to arguments
var argv = new List<string>()
{
Path.GetFileName(appPath),
};
if (args.Length > 0)
{
argv.AddRange(args);
}
WriteMessage(new StartMessage()
{
Event = Trace2Event.Start,
Sid = _sid,
Time = DateTimeOffset.UtcNow,
Thread = BuildThreadName(),
File = Path.GetFileName(filePath),
Line = lineNumber,
Argv = argv,
ElapsedTime = (DateTimeOffset.UtcNow - _applicationStartTime).TotalSeconds
});
}
private void WriteExit(int code, string filePath = "", int lineNumber = 0)
{
EnsureArgument.NotNull(code, nameof(code));
WriteMessage(new ExitMessage()
{
Event = Trace2Event.Exit,
Sid = _sid,
Time = DateTimeOffset.UtcNow,
Thread = BuildThreadName(),
File = Path.GetFileName(filePath),
Line = lineNumber,
Code = code,
ElapsedTime = (DateTimeOffset.UtcNow - _applicationStartTime).TotalSeconds
});
}
private void AddWriter(ITrace2Writer writer)
{
ThrowIfDisposed();
lock (_writersLock)
{
// Try not to add the same writer more than once
if (_writers.Contains(writer))
return;
_writers.Add(writer);
}
}
private void WriteMessage(Trace2Message message)
{
ThrowIfDisposed();
if (!_initialized)
{
return;
}
lock (_writersLock)
{
if (_writers.Count == 0)
{
return;
}
foreach (var writer in _writers)
{
if (!writer.Failed)
{
writer.Write(message);
}
}
}
}
private static string BuildThreadName()
{
// If this is the entry thread, call it "main", per Trace2 convention
if (Thread.CurrentThread.ManagedThreadId == 1)
{
return "main";
}
// If this is a thread pool thread, name it as such
if (Thread.CurrentThread.IsThreadPoolThread)
{
return $"thread_pool_{Environment.CurrentManagedThreadId}";
}
// Otherwise, if the thread is named, use it!
if (!string.IsNullOrEmpty(Thread.CurrentThread.Name))
{
return Thread.CurrentThread.Name;
}
// We don't know what this thread is!
return string.Empty;
}
}