Skip to content

add dotnet-collect command that uses EventPipe #35

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

Merged
merged 2 commits into from
Oct 17, 2018
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
Binary file not shown.
7 changes: 7 additions & 0 deletions src/dotnet-monitor/dotnet-monitor.sln
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dotnet-analyze", "src\dotne
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dotnet-dump", "src\dotnet-dump\dotnet-dump.csproj", "{933327B7-87FC-4D1B-8AF4-C6A07DE30AA4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-collect", "src\dotnet-collect\dotnet-collect.csproj", "{7950F785-5724-4BE4-98FC-52BE1BD8E04B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -42,6 +44,10 @@ Global
{933327B7-87FC-4D1B-8AF4-C6A07DE30AA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{933327B7-87FC-4D1B-8AF4-C6A07DE30AA4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{933327B7-87FC-4D1B-8AF4-C6A07DE30AA4}.Release|Any CPU.Build.0 = Release|Any CPU
{7950F785-5724-4BE4-98FC-52BE1BD8E04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7950F785-5724-4BE4-98FC-52BE1BD8E04B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7950F785-5724-4BE4-98FC-52BE1BD8E04B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7950F785-5724-4BE4-98FC-52BE1BD8E04B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -51,6 +57,7 @@ Global
{993C97DD-A837-4C8B-97DA-6F11AD797485} = {2AB63881-E835-4F6C-9362-4A16156A3F2D}
{D894FA6D-6B63-450B-93A7-4120C2CDC147} = {A9AE5A6B-48A3-424D-BD94-1A7E10921551}
{933327B7-87FC-4D1B-8AF4-C6A07DE30AA4} = {A9AE5A6B-48A3-424D-BD94-1A7E10921551}
{7950F785-5724-4BE4-98FC-52BE1BD8E04B} = {A9AE5A6B-48A3-424D-BD94-1A7E10921551}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0491437C-33E9-4E6E-967C-65A7875110CE}
Expand Down
35 changes: 35 additions & 0 deletions src/dotnet-monitor/samples/SampleMonitoredApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

Expand All @@ -25,7 +26,12 @@ private static void Main(string[] args)

var logger = logging.CreateLogger<Program>();

DumpEventPipeInfo();

Console.WriteLine($"Process ID: {Process.GetCurrentProcess().Id}");
Console.WriteLine($"AppName: {Assembly.GetEntryAssembly().GetName().Name}");
Console.WriteLine($"AppDomain Base: {AppDomain.CurrentDomain.BaseDirectory}");
Console.WriteLine($"AppBase: {AppContext.BaseDirectory}");
Console.WriteLine("Ready to start emitting events.");
Console.WriteLine("Press X to quit.");
Console.WriteLine("Press A to allocate 100 MB.");
Expand Down Expand Up @@ -62,6 +68,35 @@ private static void Main(string[] args)
}
}

private static void DumpEventPipeInfo()
{
var type = typeof(ValueType).Assembly.GetType("System.Diagnostics.Tracing.EventPipeController");
if (type == null)
{
throw new InvalidOperationException("Could not find EventPipeController type!");
}

var instanceField = type.GetField("s_controllerInstance", BindingFlags.NonPublic | BindingFlags.Static);
if (instanceField == null)
{
throw new InvalidOperationException("Could not find EventPipeController.s_controllerInstance field!");
}

var instance = instanceField.GetValue(null);
if (instance == null)
{
throw new InvalidOperationException("EventPipeController.s_controllerInstance is null!");
}

var pathField = type.GetField("m_configFilePath", BindingFlags.NonPublic | BindingFlags.Instance);
if (pathField == null)
{
throw new InvalidOperationException("Could not find EventPipeController.m_configFilePath field!");
}

Console.WriteLine($"EventPipe Config File Path: {pathField.GetValue(instance)}");
}

private static void SpawnTasks()
{
var tasks = new Task[100];
Expand Down
1 change: 1 addition & 0 deletions src/dotnet-monitor/samples/SampleWebApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public class Program
public static void Main(string[] args)
{
Console.WriteLine($"Process ID: {Process.GetCurrentProcess().Id}");
Console.WriteLine($"AppBase: {AppContext.BaseDirectory}");
CreateWebHostBuilder(args).Build().Run();
}

Expand Down
14 changes: 13 additions & 1 deletion src/dotnet-monitor/src/Common/ConsoleCancellation.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading;
using System.Threading.Tasks;
using McMaster.Extensions.CommandLineUtils;

namespace Microsoft.Internal.Utilities
Expand All @@ -28,5 +28,17 @@ public static CancellationToken GetCtrlCToken(this IConsole console)
};
return cts.Token;
}

public static Task WaitForCtrlCAsync(this IConsole console)
{
var tcs = new TaskCompletionSource<object>();
console.CancelKeyPress += (sender, args) =>
{
// Don't terminate, just trip the task
args.Cancel = true;
tcs.TrySetResult(null);
};
return tcs.Task;
}
}
}
38 changes: 38 additions & 0 deletions src/dotnet-monitor/src/dotnet-collect/EventPipeConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Microsoft.Diagnostics.Tools.Collect
{
public class EventPipeConfiguration
{
public int? ProcessId { get; set; }
public string OutputPath { get; set; }
public int? CircularMB { get; set; }
public IList<EventSpec> Providers { get; set; } = new List<EventSpec>();

internal string ToConfigString()
{
var builder = new StringBuilder();
if (ProcessId != null)
{
builder.AppendLine($"ProcessId={ProcessId.Value}");
}
if (!string.IsNullOrEmpty(OutputPath))
{
builder.AppendLine($"OutputPath={OutputPath}");
}
if (CircularMB != null)
{
builder.AppendLine($"CircularMB={CircularMB}");
}
if (Providers != null && Providers.Count > 0)
{
builder.AppendLine($"Providers={SerializeProviders(Providers)}");
}
return builder.ToString();
}

private string SerializeProviders(IList<EventSpec> providers) => string.Join(",", providers.Select(s => s.ToConfigString()));
}
}
89 changes: 89 additions & 0 deletions src/dotnet-monitor/src/dotnet-collect/EventSpec.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using System;
using System.Diagnostics.Tracing;
using System.Globalization;

namespace Microsoft.Diagnostics.Tools.Collect
{
public class EventSpec
{
public string Provider { get; }
public ulong Keywords { get; }
public EventLevel Level { get; }

public EventSpec(string provider, ulong keywords, EventLevel level)
{
Provider = provider;
Keywords = keywords;
Level = level;
}

public static bool TryParse(string input, out EventSpec spec)
{
spec = null;
var splat = input.Split(':');

if (splat.Length == 0)
{
return false;
}

var provider = splat[0];
var keywords = ulong.MaxValue;
var level = EventLevel.Verbose;

if (splat.Length > 1)
{
if (!TryParseKeywords(splat[1], out keywords) && !TryParseLevel(splat[1], out level))
{
return false;
}
}

if (splat.Length > 2)
{
if (!TryParseLevel(splat[1], out level))
{
return false;
}
}

spec = new EventSpec(provider, keywords, level);
return true;
}

public string ToConfigString() => $"{Provider}:0x{Keywords:X}:{(int)Level}";

private static bool TryParseLevel(string input, out EventLevel level)
{
level = EventLevel.Verbose;
if (int.TryParse(input, out var intLevel))
{
if (intLevel >= (int)EventLevel.LogAlways && intLevel <= (int)EventLevel.Verbose)
{
level = (EventLevel)intLevel;
return true;
}
}
else if (Enum.TryParse(input, ignoreCase: true, out level))
{
return true;
}
return false;
}

private static bool TryParseKeywords(string input, out ulong keywords)
{
if (input.StartsWith("0x"))
{
// Keywords
if (ulong.TryParse(input, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out keywords))
{
return true;
}
}

keywords = ulong.MaxValue;
return false;
}
}
}
101 changes: 101 additions & 0 deletions src/dotnet-monitor/src/dotnet-collect/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Threading.Tasks;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Internal.Utilities;

namespace Microsoft.Diagnostics.Tools.Collect
{
[Command(Name = "dotnet-collect", Description = "Collects Event Traces from .NET processes")]
internal class Program
{
[Required(ErrorMessage = "You must provide the path of the EventPipe config file to write")]
[Option("-c|--config-path <CONFIG_PATH>", Description = "The path of the EventPipe config file to write, must be named [AppName].eventpipeconfig and be in the base directory for a managed app.")]
public string ConfigPath { get; set; }

[Option("-p|--process-id <PROCESS_ID>", Description = "Filter to only the process with the specified process ID.")]
public int? ProcessId { get; set; }

[Option("-o|--output <OUTPUT_DIRECTORY>", Description = "The directory to write the trace to. Defaults to the current working directory.")]
public string OutputDir { get; set; }

[Option("--buffer <BUFFER_SIZE_IN_MB>", Description = "The size of the in-memory circular buffer in megabytes.")]
public int? CircularMB { get; set; }

[Option("--provider <PROVIDER_SPEC>", Description = "An EventPipe provider to enable. A string in the form '<provider name>:<keywords>:<level>'. Can be specified multiple times to enable multiple providers.")]
public IList<string> Providers { get; set; }

public async Task<int> OnExecute(IConsole console, CommandLineApplication app)
{
if (File.Exists(ConfigPath))
{
console.Error.WriteLine("Config file already exists, tracing is already underway by a different consumer.");
return 1;
}

var appBase = Path.GetDirectoryName(ConfigPath);
var appName = Path.GetFileNameWithoutExtension(ConfigPath);

var config = new EventPipeConfiguration()
{
ProcessId = ProcessId,
CircularMB = CircularMB,
OutputPath = string.IsNullOrEmpty(OutputDir) ? Directory.GetCurrentDirectory() : OutputDir
};

if (Providers != null && Providers.Count > 0)
{
foreach (var provider in Providers)
{
if (!EventSpec.TryParse(provider, out var spec))
{
console.Error.WriteLine($"Invalid provider specification: '{provider}'. A provider specification must be in one of the following formats:");
console.Error.WriteLine(" <providerName> - Enable all events at all levels for the provider.");
console.Error.WriteLine(" <providerName>:<keywords> - Enable events matching the specified keywords for the specified provider.");
console.Error.WriteLine(" <providerName>:<level> - Enable events at the specified level for the provider.");
console.Error.WriteLine(" <providerName>:<keywords>:<level> - Enable events matching the specified keywords, at the specified level for the specified provider.");
console.Error.WriteLine("");
console.Error.WriteLine("'<provider>' must be the name of the EventSource.");
console.Error.WriteLine("'<level>' can be one of: Critical (1), Error (2), Warning (3), Informational (4), Verbose (5). Either the name or number can be specified.");
console.Error.WriteLine("'<keywords>' is a hexadecimal number, starting with '0x', defining the keywords to enable.");
return 1;
}
config.Providers.Add(spec);
}
}

// Write the config file contents
var configContent = config.ToConfigString();
File.WriteAllText(ConfigPath, configContent);
console.WriteLine("Tracing has started. Press Ctrl-C to stop.");

await console.WaitForCtrlCAsync();

File.Delete(ConfigPath);
console.WriteLine($"Tracing stopped. Trace files written to {config.OutputPath}");

return 0;
}

private static int Main(string[] args)
{
DebugUtil.WaitForDebuggerIfRequested(ref args);

try
{
return CommandLineApplication.Execute<Program>(args);
}
catch (PlatformNotSupportedException ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
catch (OperationCanceledException)
{
return 0;
}
}
}
}
18 changes: 18 additions & 0 deletions src/dotnet-monitor/src/dotnet-collect/dotnet-collect.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Microsoft.Diagnostics.Tools.Collect</RootNamespace>
</PropertyGroup>

<ItemGroup>
<Compile Include="..\Common\ConsoleCancellation.cs" Link="ConsoleCancellation.cs" />
<Compile Include="..\Common\DebugUtil.cs" Link="DebugUtil.cs" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="2.2.5" />
</ItemGroup>

</Project>