Skip to content
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
536cd50
[DotnetTrace] Update CLREventKeywords
mdh1418 Sep 16, 2025
49a875b
[DotnetTrace] Move MergeProfileAndProviders to Extensions
mdh1418 Sep 17, 2025
b4787fc
[DotnetTrace] Rename Extensions to ProviderUtils
mdh1418 Sep 17, 2025
c921869
[DotnetTrace] Add provider unifying helper
mdh1418 Sep 17, 2025
e1c15c7
[DotnetTrace] Move shared options to CommonOptions
mdh1418 Sep 17, 2025
b4112b5
[DotnetTrace] Add collect-linux skeleton
mdh1418 Sep 17, 2025
e5f3975
[DotnetTrace][CollectLinux] Start record-trace
mdh1418 Sep 17, 2025
677e54e
[DotnetTrace][CollectLinux] Build record-trace args
mdh1418 Sep 17, 2025
31186a8
[DotnetTrace] Update profiles
mdh1418 Sep 17, 2025
44593bb
[DotnetTrace] Update collect to new provider unifier
mdh1418 Sep 17, 2025
b190d73
[DotnetCounters] Remove Extensions reference
mdh1418 Sep 19, 2025
9f1ef6d
[DotnetTrace] Update tests
mdh1418 Sep 19, 2025
c8e53ea
Address Feedback
mdh1418 Sep 19, 2025
590a203
[DotnetTrace] Print profile effects and clrevents ignore warning
mdh1418 Sep 19, 2025
8e2453f
[DotnetTrace] Print PerfEvents and include in default condition
mdh1418 Sep 19, 2025
573d769
[DotnetTrace] Update OneCollect package with FFI
mdh1418 Sep 30, 2025
1b3b583
Fix dotnet-trace build for repo root build
mdh1418 Oct 3, 2025
e6d9de9
Add Linux events table
mdh1418 Oct 6, 2025
676efa9
Add Progress status and Address feedback
mdh1418 Oct 6, 2025
d90d1be
Merge remote-tracking branch 'upstream/main' into dotnet_trace_collec…
mdh1418 Oct 6, 2025
096f325
Update collect functional tests for ProviderUtils refactor
mdh1418 Oct 6, 2025
1f75125
[DotnetTrace] Add Collect Linux Functional Tests
mdh1418 Oct 6, 2025
55bc84a
Adjust CollectLinux tests for non-Linux platforms
mdh1418 Oct 7, 2025
4c1a361
[DotnetTrace][CollectLinux] Remove process specifier
mdh1418 Oct 7, 2025
208086f
Adjust functional tests and add failure cases
mdh1418 Oct 8, 2025
40c5905
[DotnetTrace][CollectLinux] Add ProgressStatus and output file to tests
mdh1418 Oct 8, 2025
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
1 change: 1 addition & 0 deletions src/Tools/Common/Commands/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ internal enum ReturnCode
SessionCreationError,
TracingError,
ArgumentError,
PlatformNotSupportedError,
UnknownError
}
}
83 changes: 18 additions & 65 deletions src/Tools/dotnet-trace/CommandLine/Commands/CollectCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ private static async Task<int> Collect(CancellationToken ct, CommandLineConfigur

Dictionary<string, string> enabledBy = new();

List<EventPipeProvider> providerCollection = Extensions.ToProviders(providers);
List<EventPipeProvider> providerCollection = ProviderUtils.ToProviders(providers);
foreach (EventPipeProvider providerCollectionProvider in providerCollection)
{
enabledBy[providerCollectionProvider.Name] = "--providers ";
Expand All @@ -138,7 +138,7 @@ private static async Task<int> Collect(CancellationToken ct, CommandLineConfigur
rundownKeyword = selectedProfile.RundownKeyword;
retryStrategy = selectedProfile.RetryStrategy;

Profile.MergeProfileAndProviders(selectedProfile, providerCollection, enabledBy);
ProviderUtils.MergeProfileAndProviders(selectedProfile, providerCollection, enabledBy);
}

if (rundown.HasValue)
Expand All @@ -159,15 +159,15 @@ private static async Task<int> Collect(CancellationToken ct, CommandLineConfigur
if (clrevents.Length != 0)
{
// Ignore --clrevents if CLR event provider was already specified via --profile or --providers command.
if (enabledBy.ContainsKey(Extensions.CLREventProviderName))
if (enabledBy.ContainsKey(ProviderUtils.CLREventProviderName))
{
ConsoleWriteLine($"The argument --clrevents {clrevents} will be ignored because the CLR provider was configured via either --profile or --providers command.");
}
else
{
EventPipeProvider clrProvider = Extensions.ToCLREventPipeProvider(clrevents, clreventlevel);
EventPipeProvider clrProvider = ProviderUtils.ToCLREventPipeProvider(clrevents, clreventlevel);
providerCollection.Add(clrProvider);
enabledBy[Extensions.CLREventProviderName] = "--clrevents";
enabledBy[ProviderUtils.CLREventProviderName] = "--clrevents";
}
}

Expand Down Expand Up @@ -263,7 +263,7 @@ private static async Task<int> Collect(CancellationToken ct, CommandLineConfigur

}

if (string.Equals(output.Name, DefaultTraceName, StringComparison.OrdinalIgnoreCase))
if (string.Equals(output.Name, CommonOptions.DefaultTraceName, StringComparison.OrdinalIgnoreCase))
{
DateTime now = DateTime.Now;
FileInfo processMainModuleFileInfo = new(processMainModuleFileName);
Expand Down Expand Up @@ -565,13 +565,13 @@ public static Command CollectCommand()
// Options
CommonOptions.ProcessIdOption,
CircularBufferOption,
OutputPathOption,
ProvidersOption,
ProfileOption,
CommonOptions.OutputPathOption,
CommonOptions.ProvidersOption,
CommonOptions.ProfileOption,
CommonOptions.FormatOption,
DurationOption,
CLREventsOption,
CLREventLevelOption,
CommonOptions.DurationOption,
CommonOptions.CLREventsOption,
CommonOptions.CLREventLevelOption,
CommonOptions.NameOption,
DiagnosticPortOption,
ShowChildIOOption,
Expand All @@ -589,14 +589,14 @@ public static Command CollectCommand()
ct,
cliConfig: parseResult.Configuration,
processId: parseResult.GetValue(CommonOptions.ProcessIdOption),
output: parseResult.GetValue(OutputPathOption),
output: parseResult.GetValue(CommonOptions.OutputPathOption),
buffersize: parseResult.GetValue(CircularBufferOption),
providers: parseResult.GetValue(ProvidersOption) ?? string.Empty,
profile: parseResult.GetValue(ProfileOption) ?? string.Empty,
providers: parseResult.GetValue(CommonOptions.ProvidersOption) ?? string.Empty,
profile: parseResult.GetValue(CommonOptions.ProfileOption) ?? string.Empty,
format: parseResult.GetValue(CommonOptions.FormatOption),
duration: parseResult.GetValue(DurationOption),
clrevents: parseResult.GetValue(CLREventsOption) ?? string.Empty,
clreventlevel: parseResult.GetValue(CLREventLevelOption) ?? string.Empty,
duration: parseResult.GetValue(CommonOptions.DurationOption),
clrevents: parseResult.GetValue(CommonOptions.CLREventsOption) ?? string.Empty,
clreventlevel: parseResult.GetValue(CommonOptions.CLREventLevelOption) ?? string.Empty,
name: parseResult.GetValue(CommonOptions.NameOption),
diagnosticPort: parseResult.GetValue(DiagnosticPortOption) ?? string.Empty,
showchildio: parseResult.GetValue(ShowChildIOOption),
Expand All @@ -619,53 +619,6 @@ public static Command CollectCommand()
DefaultValueFactory = _ => DefaultCircularBufferSizeInMB,
};

public static string DefaultTraceName => "default";

private static readonly Option<FileInfo> OutputPathOption =
new("--output", "-o")
{
Description = $"The output path for the collected trace data. If not specified it defaults to '<appname>_<yyyyMMdd>_<HHmmss>.nettrace', e.g., 'myapp_20210315_111514.nettrace'.",
DefaultValueFactory = _ => new FileInfo(DefaultTraceName)
};

private static readonly Option<string> ProvidersOption =
new("--providers")
{
Description = @"A comma delimitted list of EventPipe providers to be enabled. This is in the form 'Provider[,Provider]'," +
@"where Provider is in the form: 'KnownProviderName[:[Flags][:[Level][:[KeyValueArgs]]]]', and KeyValueArgs is in the form: " +
@"'[key1=value1][;key2=value2]'. Values in KeyValueArgs that contain ';' or '=' characters need to be surrounded by '""', " +
@"e.g., FilterAndPayloadSpecs=""MyProvider/MyEvent:-Prop1=Prop1;Prop2=Prop2.A.B;"". Depending on your shell, you may need to " +
@"escape the '""' characters and/or surround the entire provider specification in quotes, e.g., " +
@"--providers 'KnownProviderName:0x1:1:FilterSpec=\""KnownProviderName/EventName:-Prop1=Prop1;Prop2=Prop2.A.B;\""'. These providers are in " +
@"addition to any providers implied by the --profile argument. If there is any discrepancy for a particular provider, the " +
@"configuration here takes precedence over the implicit configuration from the profile. See documentation for examples."
// TODO: Can we specify an actual type?
};

private static readonly Option<string> ProfileOption =
new("--profile")
{
Description = @"A named pre-defined set of provider configurations that allows common tracing scenarios to be specified succinctly."
};

private static readonly Option<TimeSpan> DurationOption =
new("--duration")
{
Description = @"When specified, will trace for the given timespan and then automatically stop the trace. Provided in the form of dd:hh:mm:ss."
};

private static readonly Option<string> CLREventsOption =
new("--clrevents")
{
Description = @"List of CLR runtime events to emit."
};

private static readonly Option<string> CLREventLevelOption =
new("--clreventlevel")
{
Description = @"Verbosity of CLR events to be emitted."
};

private static readonly Option<string> DiagnosticPortOption =
new("--diagnostic-port", "--dport")
{
Expand Down
185 changes: 185 additions & 0 deletions src/Tools/dotnet-trace/CommandLine/Commands/CollectLinuxCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Internal.Common.Utils;

namespace Microsoft.Diagnostics.Tools.Trace
{
internal static partial class CollectLinuxCommandHandler
{
private static int s_recordStatus;

internal sealed record CollectLinuxArgs(
string[] Providers,
string ClrEventLevel,
string ClrEvents,
string[] PerfEvents,
string[] Profiles,
FileInfo Output,
TimeSpan Duration,
string Name,
int ProcessId);

/// <summary>
/// Collects diagnostic traces using perf_events, a Linux OS technology. collect-linux requires admin privileges to capture kernel- and user-mode events, and by default, captures events from all processes.
/// This Linux-only command includes the same .NET events as dotnet-trace collect, and it uses the kernel’s user_events mechanism to emit .NET events as perf events, enabling unification of user-space .NET events with kernel-space system events.
/// </summary>
private static int CollectLinux(CollectLinuxArgs args)
{
if (!OperatingSystem.IsLinux())
{
Console.Error.WriteLine("The collect-linux command is only supported on Linux.");
return (int)ReturnCode.ArgumentError;
}

return RunRecordTrace(args);
}

public static Command CollectLinuxCommand()
{
Command collectLinuxCommand = new("collect-linux")
{
CommonOptions.ProvidersOption,
CommonOptions.CLREventLevelOption,
CommonOptions.CLREventsOption,
PerfEventsOption,
CommonOptions.ProfileOption,
CommonOptions.OutputPathOption,
CommonOptions.DurationOption,
CommonOptions.NameOption,
CommonOptions.ProcessIdOption
};
collectLinuxCommand.TreatUnmatchedTokensAsErrors = true; // collect-linux currently does not support child process tracing.
collectLinuxCommand.Description = "Collects diagnostic traces using perf_events, a Linux OS technology. collect-linux requires admin privileges to capture kernel- and user-mode events, and by default, captures events from all processes. This Linux-only command includes the same .NET events as dotnet-trace collect, and it uses the kernel’s user_events mechanism to emit .NET events as perf events, enabling unification of user-space .NET events with kernel-space system events.";

collectLinuxCommand.SetAction((parseResult, ct) => {
string providersValue = parseResult.GetValue(CommonOptions.ProvidersOption) ?? string.Empty;
string perfEventsValue = parseResult.GetValue(PerfEventsOption) ?? string.Empty;
string profilesValue = parseResult.GetValue(CommonOptions.ProfileOption) ?? string.Empty;

int rc = CollectLinux(new CollectLinuxArgs(
Providers: providersValue.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
ClrEventLevel: parseResult.GetValue(CommonOptions.CLREventLevelOption) ?? string.Empty,
ClrEvents: parseResult.GetValue(CommonOptions.CLREventsOption) ?? string.Empty,
PerfEvents: perfEventsValue.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
Profiles: profilesValue.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
Output: parseResult.GetValue(CommonOptions.OutputPathOption) ?? new FileInfo(CommonOptions.DefaultTraceName),
Duration: parseResult.GetValue(CommonOptions.DurationOption),
Name: parseResult.GetValue(CommonOptions.NameOption) ?? string.Empty,
ProcessId: parseResult.GetValue(CommonOptions.ProcessIdOption)));
return Task.FromResult(rc);
});

return collectLinuxCommand;
}

private static int RunRecordTrace(CollectLinuxArgs args)
{
s_recordStatus = 0;

ConsoleCancelEventHandler handler = (sender, e) =>
{
e.Cancel = true;
s_recordStatus = 1;
};
Console.CancelKeyPress += handler;

IEnumerable<string> recordTraceArgList = BuildRecordTraceArgs(args, out string scriptPath);

string options = string.Join(' ', recordTraceArgList);
byte[] command = Encoding.UTF8.GetBytes(options);
int rc;
try
{
rc = RecordTrace(command, (UIntPtr)command.Length, OutputHandler);
}
finally
{
Console.CancelKeyPress -= handler;
if (!string.IsNullOrEmpty(scriptPath))
{
try {
if (File.Exists(scriptPath))
{
File.Delete(scriptPath);
}
} catch { }
}
}

return rc;
}

private static List<string> BuildRecordTraceArgs(CollectLinuxArgs args, out string scriptPath)
{
Console.WriteLine($"{args.ProcessId}");
List<string> recordTraceArgs = new();

recordTraceArgs.Add("--on-cpu");

return recordTraceArgs;
}

private static int OutputHandler(uint type, IntPtr data, UIntPtr dataLen)
{
OutputType ot = (OutputType)type;
if (ot != OutputType.Progress)
{
int len = checked((int)dataLen);
if (len > 0)
{
byte[] buffer = new byte[len];
Marshal.Copy(data, buffer, 0, len);
string text = Encoding.UTF8.GetString(buffer);
switch (ot)
{
case OutputType.Normal:
case OutputType.Live:
Console.Out.WriteLine(text);
break;
case OutputType.Error:
Console.Error.WriteLine(text);
break;
default:
Console.Error.WriteLine($"[{ot}] {text}");
break;
}
}
}

return s_recordStatus;
}

private static readonly Option<string> PerfEventsOption =
new("--perf-events")
{
Description = @"Comma-separated list of kernel perf events (e.g. syscalls:sys_enter_execve,sched:sched_switch)."
};

private enum OutputType : uint
{
Normal = 0,
Live = 1,
Error = 2,
Progress = 3,
}

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int recordTraceCallback(
[In] uint type,
[In] IntPtr data,
[In] UIntPtr dataLen);

[LibraryImport("recordtrace")]
private static partial int RecordTrace(
byte[] command,
UIntPtr commandLen,
recordTraceCallback callback);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ public static Command ConvertCommand()
private static readonly Argument<FileInfo> InputFileArgument =
new Argument<FileInfo>(name: "input-filename")
{
Description = $"Input trace file to be converted. Defaults to '{CollectCommandHandler.DefaultTraceName}'.",
DefaultValueFactory = _ => new FileInfo(CollectCommandHandler.DefaultTraceName),
Description = $"Input trace file to be converted. Defaults to '{CommonOptions.DefaultTraceName}'.",
DefaultValueFactory = _ => new FileInfo(CommonOptions.DefaultTraceName),
}.AcceptExistingOnly();

private static readonly Option<FileInfo> OutputOption =
Expand Down
Loading