|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.CommandLine; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.IO; |
| 8 | +using System.Linq; |
| 9 | +using System.Runtime.InteropServices; |
| 10 | +using System.Text; |
| 11 | +using System.Threading; |
| 12 | +using System.Threading.Tasks; |
| 13 | +using Microsoft.Diagnostics.NETCore.Client; |
| 14 | +using Microsoft.Diagnostics.Tools.Common; |
| 15 | +using Microsoft.Internal.Common.Utils; |
| 16 | + |
| 17 | +namespace Microsoft.Diagnostics.Tools.Trace |
| 18 | +{ |
| 19 | + internal partial class CollectLinuxCommandHandler |
| 20 | + { |
| 21 | + private bool stopTracing; |
| 22 | + private Stopwatch stopwatch = new(); |
| 23 | + private LineRewriter rewriter; |
| 24 | + private bool printingStatus; |
| 25 | + |
| 26 | + internal sealed record CollectLinuxArgs( |
| 27 | + CancellationToken Ct, |
| 28 | + string[] Providers, |
| 29 | + string ClrEventLevel, |
| 30 | + string ClrEvents, |
| 31 | + string[] PerfEvents, |
| 32 | + string[] Profiles, |
| 33 | + FileInfo Output, |
| 34 | + TimeSpan Duration); |
| 35 | + |
| 36 | + public CollectLinuxCommandHandler(IConsole console = null) |
| 37 | + { |
| 38 | + Console = console ?? new DefaultConsole(false); |
| 39 | + rewriter = new LineRewriter(Console); |
| 40 | + } |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// 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. |
| 44 | + /// 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. |
| 45 | + /// </summary> |
| 46 | + internal int CollectLinux(CollectLinuxArgs args) |
| 47 | + { |
| 48 | + if (!OperatingSystem.IsLinux()) |
| 49 | + { |
| 50 | + Console.Error.WriteLine("The collect-linux command is only supported on Linux."); |
| 51 | + return (int)ReturnCode.PlatformNotSupportedError; |
| 52 | + } |
| 53 | + |
| 54 | + Console.WriteLine("=========================================================================================="); |
| 55 | + Console.WriteLine("The collect-linux verb is a new preview feature and relies on an updated version of the"); |
| 56 | + Console.WriteLine(".nettrace file format. The latest PerfView release supports these trace files but other"); |
| 57 | + Console.WriteLine("ways of using the trace file may not work yet. For more details, see the docs at"); |
| 58 | + Console.WriteLine("https://learn.microsoft.com/dotnet/core/diagnostics/dotnet-trace."); |
| 59 | + Console.WriteLine("=========================================================================================="); |
| 60 | + |
| 61 | + args.Ct.Register(() => stopTracing = true); |
| 62 | + int ret = (int)ReturnCode.TracingError; |
| 63 | + string scriptPath = null; |
| 64 | + try |
| 65 | + { |
| 66 | + Console.CursorVisible = false; |
| 67 | + byte[] command = BuildRecordTraceArgs(args, out scriptPath); |
| 68 | + |
| 69 | + if (args.Duration != default) |
| 70 | + { |
| 71 | + System.Timers.Timer durationTimer = new(args.Duration.TotalMilliseconds); |
| 72 | + durationTimer.Elapsed += (sender, e) => |
| 73 | + { |
| 74 | + durationTimer.Stop(); |
| 75 | + stopTracing = true; |
| 76 | + }; |
| 77 | + durationTimer.Start(); |
| 78 | + } |
| 79 | + stopwatch.Start(); |
| 80 | + ret = RecordTraceInvoker(command, (UIntPtr)command.Length, OutputHandler); |
| 81 | + } |
| 82 | + catch (CommandLineErrorException e) |
| 83 | + { |
| 84 | + Console.Error.WriteLine($"[ERROR] {e.Message}"); |
| 85 | + ret = (int)ReturnCode.TracingError; |
| 86 | + } |
| 87 | + catch (Exception ex) |
| 88 | + { |
| 89 | + Console.Error.WriteLine($"[ERROR] {ex}"); |
| 90 | + ret = (int)ReturnCode.TracingError; |
| 91 | + } |
| 92 | + finally |
| 93 | + { |
| 94 | + if (!string.IsNullOrEmpty(scriptPath)) |
| 95 | + { |
| 96 | + try |
| 97 | + { |
| 98 | + if (File.Exists(scriptPath)) |
| 99 | + { |
| 100 | + File.Delete(scriptPath); |
| 101 | + } |
| 102 | + } catch { } |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + return ret; |
| 107 | + } |
| 108 | + |
| 109 | + public static Command CollectLinuxCommand() |
| 110 | + { |
| 111 | + Command collectLinuxCommand = new("collect-linux") |
| 112 | + { |
| 113 | + CommonOptions.ProvidersOption, |
| 114 | + CommonOptions.CLREventLevelOption, |
| 115 | + CommonOptions.CLREventsOption, |
| 116 | + PerfEventsOption, |
| 117 | + CommonOptions.ProfileOption, |
| 118 | + CommonOptions.OutputPathOption, |
| 119 | + CommonOptions.DurationOption, |
| 120 | + }; |
| 121 | + collectLinuxCommand.TreatUnmatchedTokensAsErrors = true; // collect-linux currently does not support child process tracing. |
| 122 | + 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."; |
| 123 | + |
| 124 | + collectLinuxCommand.SetAction((parseResult, ct) => { |
| 125 | + string providersValue = parseResult.GetValue(CommonOptions.ProvidersOption) ?? string.Empty; |
| 126 | + string perfEventsValue = parseResult.GetValue(PerfEventsOption) ?? string.Empty; |
| 127 | + string profilesValue = parseResult.GetValue(CommonOptions.ProfileOption) ?? string.Empty; |
| 128 | + CollectLinuxCommandHandler handler = new(); |
| 129 | + |
| 130 | + int rc = handler.CollectLinux(new CollectLinuxArgs( |
| 131 | + Ct: ct, |
| 132 | + Providers: providersValue.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), |
| 133 | + ClrEventLevel: parseResult.GetValue(CommonOptions.CLREventLevelOption) ?? string.Empty, |
| 134 | + ClrEvents: parseResult.GetValue(CommonOptions.CLREventsOption) ?? string.Empty, |
| 135 | + PerfEvents: perfEventsValue.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), |
| 136 | + Profiles: profilesValue.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), |
| 137 | + Output: parseResult.GetValue(CommonOptions.OutputPathOption) ?? new FileInfo(CommonOptions.DefaultTraceName), |
| 138 | + Duration: parseResult.GetValue(CommonOptions.DurationOption))); |
| 139 | + return Task.FromResult(rc); |
| 140 | + }); |
| 141 | + |
| 142 | + return collectLinuxCommand; |
| 143 | + } |
| 144 | + |
| 145 | + private byte[] BuildRecordTraceArgs(CollectLinuxArgs args, out string scriptPath) |
| 146 | + { |
| 147 | + scriptPath = null; |
| 148 | + List<string> recordTraceArgs = new(); |
| 149 | + |
| 150 | + string[] profiles = args.Profiles; |
| 151 | + if (args.Profiles.Length == 0 && args.Providers.Length == 0 && string.IsNullOrEmpty(args.ClrEvents) && args.PerfEvents.Length == 0) |
| 152 | + { |
| 153 | + Console.WriteLine("No providers, profiles, ClrEvents, or PerfEvents were specified, defaulting to trace profiles 'dotnet-common' + 'cpu-sampling'."); |
| 154 | + profiles = new[] { "dotnet-common", "cpu-sampling" }; |
| 155 | + } |
| 156 | + |
| 157 | + StringBuilder scriptBuilder = new(); |
| 158 | + List<EventPipeProvider> providerCollection = ProviderUtils.ComputeProviderConfig(args.Providers, args.ClrEvents, args.ClrEventLevel, profiles, true, "collect-linux", Console); |
| 159 | + foreach (EventPipeProvider provider in providerCollection) |
| 160 | + { |
| 161 | + string providerName = provider.Name; |
| 162 | + string providerNameSanitized = providerName.Replace('-', '_').Replace('.', '_'); |
| 163 | + long keywords = provider.Keywords; |
| 164 | + uint eventLevel = (uint)provider.EventLevel; |
| 165 | + IDictionary<string, string> arguments = provider.Arguments; |
| 166 | + if (arguments != null && arguments.Count > 0) |
| 167 | + { |
| 168 | + scriptBuilder.Append($"set_dotnet_filter_args(\n\t\"{providerName}\""); |
| 169 | + foreach ((string key, string value) in arguments) |
| 170 | + { |
| 171 | + scriptBuilder.Append($",\n\t\"{key}={value}\""); |
| 172 | + } |
| 173 | + scriptBuilder.Append($");\n"); |
| 174 | + } |
| 175 | + |
| 176 | + scriptBuilder.Append($"let {providerNameSanitized}_flags = new_dotnet_provider_flags();\n"); |
| 177 | + scriptBuilder.Append($"record_dotnet_provider(\"{providerName}\", 0x{keywords:X}, {eventLevel}, {providerNameSanitized}_flags);\n\n"); |
| 178 | + } |
| 179 | + |
| 180 | + List<string> linuxEventLines = new(); |
| 181 | + foreach (string profile in profiles) |
| 182 | + { |
| 183 | + Profile traceProfile = ListProfilesCommandHandler.TraceProfiles |
| 184 | + .FirstOrDefault(p => p.Name.Equals(profile, StringComparison.OrdinalIgnoreCase)); |
| 185 | + |
| 186 | + if (traceProfile != null && |
| 187 | + !string.IsNullOrEmpty(traceProfile.VerbExclusivity) && |
| 188 | + traceProfile.VerbExclusivity.Equals("collect-linux", StringComparison.OrdinalIgnoreCase)) |
| 189 | + { |
| 190 | + recordTraceArgs.Add(traceProfile.CollectLinuxArgs); |
| 191 | + linuxEventLines.Add($"{traceProfile.Name,-80}--profile"); |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + foreach (string perfEvent in args.PerfEvents) |
| 196 | + { |
| 197 | + string[] split = perfEvent.Split(':', 2, StringSplitOptions.TrimEntries); |
| 198 | + if (split.Length != 2 || string.IsNullOrEmpty(split[0]) || string.IsNullOrEmpty(split[1])) |
| 199 | + { |
| 200 | + throw new CommandLineErrorException($"Invalid perf event specification '{perfEvent}'. Expected format 'provider:event'."); |
| 201 | + } |
| 202 | + |
| 203 | + string perfProvider = split[0]; |
| 204 | + string perfEventName = split[1]; |
| 205 | + linuxEventLines.Add($"{perfEvent,-80}--perf-events"); |
| 206 | + scriptBuilder.Append($"let {perfEventName} = event_from_tracefs(\"{perfProvider}\", \"{perfEventName}\");\nrecord_event({perfEventName});\n\n"); |
| 207 | + } |
| 208 | + |
| 209 | + if (linuxEventLines.Count > 0) |
| 210 | + { |
| 211 | + Console.WriteLine($"{("Linux Perf Events"),-80}Enabled By"); |
| 212 | + foreach (string line in linuxEventLines) |
| 213 | + { |
| 214 | + Console.WriteLine(line); |
| 215 | + } |
| 216 | + } |
| 217 | + else |
| 218 | + { |
| 219 | + Console.WriteLine("No Linux Perf Events enabled."); |
| 220 | + } |
| 221 | + Console.WriteLine(); |
| 222 | + |
| 223 | + FileInfo resolvedOutput = ResolveOutputPath(args.Output); |
| 224 | + recordTraceArgs.Add($"--out"); |
| 225 | + recordTraceArgs.Add(resolvedOutput.FullName); |
| 226 | + Console.WriteLine($"Output File : {resolvedOutput.FullName}"); |
| 227 | + Console.WriteLine(); |
| 228 | + |
| 229 | + string scriptText = scriptBuilder.ToString(); |
| 230 | + scriptPath = Path.ChangeExtension(resolvedOutput.FullName, ".script"); |
| 231 | + File.WriteAllText(scriptPath, scriptText); |
| 232 | + |
| 233 | + recordTraceArgs.Add("--script-file"); |
| 234 | + recordTraceArgs.Add(scriptPath); |
| 235 | + |
| 236 | + string options = string.Join(' ', recordTraceArgs); |
| 237 | + return Encoding.UTF8.GetBytes(options); |
| 238 | + } |
| 239 | + |
| 240 | + private static FileInfo ResolveOutputPath(FileInfo output) |
| 241 | + { |
| 242 | + if (!string.Equals(output.Name, CommonOptions.DefaultTraceName, StringComparison.OrdinalIgnoreCase)) |
| 243 | + { |
| 244 | + return output; |
| 245 | + } |
| 246 | + |
| 247 | + DateTime now = DateTime.Now; |
| 248 | + return new FileInfo($"trace_{now:yyyyMMdd}_{now:HHmmss}.nettrace"); |
| 249 | + } |
| 250 | + |
| 251 | + private int OutputHandler(uint type, IntPtr data, UIntPtr dataLen) |
| 252 | + { |
| 253 | + OutputType ot = (OutputType)type; |
| 254 | + if (dataLen != UIntPtr.Zero && (ulong)dataLen <= int.MaxValue) |
| 255 | + { |
| 256 | + string text = Marshal.PtrToStringUTF8(data, (int)dataLen); |
| 257 | + if (!string.IsNullOrEmpty(text) && |
| 258 | + !text.StartsWith("Recording started", StringComparison.OrdinalIgnoreCase)) |
| 259 | + { |
| 260 | + if (ot == OutputType.Error) |
| 261 | + { |
| 262 | + Console.Error.WriteLine(text); |
| 263 | + stopTracing = true; |
| 264 | + } |
| 265 | + else |
| 266 | + { |
| 267 | + Console.Out.WriteLine(text); |
| 268 | + } |
| 269 | + } |
| 270 | + } |
| 271 | + |
| 272 | + if (ot == OutputType.Progress) |
| 273 | + { |
| 274 | + if (printingStatus) |
| 275 | + { |
| 276 | + rewriter.RewriteConsoleLine(); |
| 277 | + } |
| 278 | + else |
| 279 | + { |
| 280 | + printingStatus = true; |
| 281 | + rewriter.LineToClear = Console.CursorTop - 1; |
| 282 | + } |
| 283 | + Console.Out.WriteLine($"[{stopwatch.Elapsed:dd\\:hh\\:mm\\:ss}]\tRecording trace."); |
| 284 | + Console.Out.WriteLine("Press <Enter> or <Ctrl-C> to exit..."); |
| 285 | + |
| 286 | + if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter) |
| 287 | + { |
| 288 | + stopTracing = true; |
| 289 | + } |
| 290 | + } |
| 291 | + |
| 292 | + return stopTracing ? 1 : 0; |
| 293 | + } |
| 294 | + |
| 295 | + private static readonly Option<string> PerfEventsOption = |
| 296 | + new("--perf-events") |
| 297 | + { |
| 298 | + Description = @"Comma-separated list of perf events (e.g. syscalls:sys_enter_execve,sched:sched_switch)." |
| 299 | + }; |
| 300 | + |
| 301 | + private enum OutputType : uint |
| 302 | + { |
| 303 | + Normal = 0, |
| 304 | + Live = 1, |
| 305 | + Error = 2, |
| 306 | + Progress = 3, |
| 307 | + } |
| 308 | + |
| 309 | + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] |
| 310 | + internal delegate int recordTraceCallback( |
| 311 | + [In] uint type, |
| 312 | + [In] IntPtr data, |
| 313 | + [In] UIntPtr dataLen); |
| 314 | + |
| 315 | + [LibraryImport("recordtrace", EntryPoint = "RecordTrace")] |
| 316 | + private static partial int RunRecordTrace( |
| 317 | + byte[] command, |
| 318 | + UIntPtr commandLen, |
| 319 | + recordTraceCallback callback); |
| 320 | + |
| 321 | +#region testing seams |
| 322 | + internal Func<byte[], UIntPtr, recordTraceCallback, int> RecordTraceInvoker { get; set; } = RunRecordTrace; |
| 323 | + internal IConsole Console { get; set; } |
| 324 | +#endregion |
| 325 | + } |
| 326 | +} |
0 commit comments