|
| 1 | +// <copyright file="TotalProcessorCount.cs" company="Datadog"> |
| 2 | +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. |
| 3 | +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. |
| 4 | +// </copyright> |
| 5 | + |
| 6 | +#if NET6_0_OR_GREATER |
| 7 | + |
| 8 | +#nullable enable |
| 9 | + |
| 10 | +using System; |
| 11 | +using System.IO; |
| 12 | +using System.Runtime.InteropServices; |
| 13 | +using Datadog.Trace.Logging; |
| 14 | +using Datadog.Trace.SourceGenerators; |
| 15 | + |
| 16 | +namespace Datadog.Trace.RuntimeMetrics; |
| 17 | + |
| 18 | +internal static class TotalProcessorCount |
| 19 | +{ |
| 20 | + private static readonly Lazy<int?> LazyValue = new(GetTotalProcessorCount); |
| 21 | + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(TotalProcessorCount)); |
| 22 | + |
| 23 | + /// <summary> |
| 24 | + /// Gets the total number of logical processors on the host machine. Differs from |
| 25 | + /// <see cref="Environment.ProcessorCount"/> (which includes cgroup/container CPU limits |
| 26 | + /// and process affinity). Mirrors the GC's own GCToOSInterface::GetTotalProcessorCount() |
| 27 | + /// </summary> |
| 28 | + public static int? Value => LazyValue.Value; |
| 29 | + |
| 30 | + [TestingAndPrivateOnly] |
| 31 | + internal static int? GetTotalProcessorCount() |
| 32 | + { |
| 33 | + if (OperatingSystem.IsWindows()) |
| 34 | + { |
| 35 | + return WindowsProcessorCount.GetTotalProcessorCount(); |
| 36 | + } |
| 37 | + |
| 38 | + if (OperatingSystem.IsLinux()) |
| 39 | + { |
| 40 | + return LinuxProcessorCount.GetTotalProcessorCount(); |
| 41 | + } |
| 42 | + |
| 43 | + if (OperatingSystem.IsMacOS()) |
| 44 | + { |
| 45 | + return MacOsProcessorCount.GetTotalProcessorCount(); |
| 46 | + } |
| 47 | + |
| 48 | + return null; |
| 49 | + } |
| 50 | + |
| 51 | + internal static class WindowsProcessorCount |
| 52 | + { |
| 53 | + private const ushort AllProcessorGroups = 0xFFFF; |
| 54 | + |
| 55 | + [DllImport("kernel32.dll", SetLastError = true)] |
| 56 | + private static extern int GetActiveProcessorCount(ushort groupNumber); |
| 57 | + |
| 58 | + /// <summary> |
| 59 | + /// Gets the total number of logical processors on a Windows host via <c>GetActiveProcessorCount</c>, |
| 60 | + /// counting active processors across all processor groups and ignoring process affinity and Job Object |
| 61 | + /// CPU limits (the container-CPU-cap mechanism on Windows). |
| 62 | + /// </summary> |
| 63 | + internal static int? GetTotalProcessorCount() |
| 64 | + { |
| 65 | + var result = GetActiveProcessorCount(AllProcessorGroups); |
| 66 | + if (result > 0) |
| 67 | + { |
| 68 | + return result; |
| 69 | + } |
| 70 | + |
| 71 | + var error = Marshal.GetLastWin32Error(); |
| 72 | + Log.Warning( |
| 73 | + "GetActiveProcessorCount failed when getting total machine processor count. ErrorCode={ErrorCode}", |
| 74 | + property: error); |
| 75 | + return null; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + internal static class LinuxProcessorCount |
| 80 | + { |
| 81 | + private const string OnlineCpusPath = "/sys/devices/system/cpu/online"; |
| 82 | + |
| 83 | + /// <summary> |
| 84 | + /// Gets the total number of logical processors on a Linux host by reading the online-CPU range |
| 85 | + /// reported by the kernel, the same source <c>sysconf(_SC_NPROCESSORS_ONLN)</c> itself reads, and unaffected |
| 86 | + /// by cgroup CPU quotas. Avoids P/Invoking into libc, which fails to resolve on musl-based images (e.g. Alpine). |
| 87 | + /// </summary> |
| 88 | + internal static int? GetTotalProcessorCount() |
| 89 | + { |
| 90 | + try |
| 91 | + { |
| 92 | + var contents = File.ReadAllText(OnlineCpusPath); |
| 93 | + return TryParseOnlineCpuRanges(contents.AsSpan()); |
| 94 | + } |
| 95 | + catch (Exception ex) |
| 96 | + { |
| 97 | + Log.Warning(ex, "Error reading {Path} to determine total machine processor count", OnlineCpusPath); |
| 98 | + return null; |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + // Parses the Linux cpu-list-format (see Documentation/admin-guide/kernel-parameters.txt) |
| 103 | + // comma-separated list of either a single CPU index ("0") or an inclusive range ("0-7"), e.g. "0-3,8-11". |
| 104 | + [TestingAndPrivateOnly] |
| 105 | + internal static int? TryParseOnlineCpuRanges(ReadOnlySpan<char> contents) |
| 106 | + { |
| 107 | + var trimmed = contents.Trim(); |
| 108 | + if (trimmed.IsEmpty) |
| 109 | + { |
| 110 | + return null; |
| 111 | + } |
| 112 | + |
| 113 | + var count = 0; |
| 114 | + var remaining = trimmed; |
| 115 | + while (!remaining.IsEmpty) |
| 116 | + { |
| 117 | + var commaIndex = remaining.IndexOf(','); |
| 118 | + var token = commaIndex < 0 ? remaining : remaining[..commaIndex]; |
| 119 | + |
| 120 | + if (!TryParseToken(token, out var tokenCount)) |
| 121 | + { |
| 122 | + return null; |
| 123 | + } |
| 124 | + |
| 125 | + count += tokenCount; |
| 126 | + |
| 127 | + if (commaIndex < 0) |
| 128 | + { |
| 129 | + break; |
| 130 | + } |
| 131 | + |
| 132 | + remaining = remaining[(commaIndex + 1)..]; |
| 133 | + if (remaining.IsEmpty) |
| 134 | + { |
| 135 | + // trailing comma with no following token |
| 136 | + return null; |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + return count > 0 ? count : null; |
| 141 | + |
| 142 | + static bool TryParseToken(ReadOnlySpan<char> token, out int tokenCount) |
| 143 | + { |
| 144 | + tokenCount = 0; |
| 145 | + |
| 146 | + var dashIndex = token.IndexOf('-'); |
| 147 | + if (dashIndex < 0) |
| 148 | + { |
| 149 | + if (!int.TryParse(token, out var single) || single < 0) |
| 150 | + { |
| 151 | + return false; |
| 152 | + } |
| 153 | + |
| 154 | + tokenCount = 1; |
| 155 | + return true; |
| 156 | + } |
| 157 | + |
| 158 | + var startSpan = token[..dashIndex]; |
| 159 | + var endSpan = token[(dashIndex + 1)..]; |
| 160 | + |
| 161 | + if (!int.TryParse(startSpan, out var start) || start < 0 || |
| 162 | + !int.TryParse(endSpan, out var end) || end < start) |
| 163 | + { |
| 164 | + return false; |
| 165 | + } |
| 166 | + |
| 167 | + tokenCount = end - start + 1; |
| 168 | + return true; |
| 169 | + } |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + internal static class MacOsProcessorCount |
| 174 | + { |
| 175 | + private const string LogicalCpuName = "hw.logicalcpu"; |
| 176 | + |
| 177 | + [DllImport("libSystem.dylib", EntryPoint = "sysctlbyname", CharSet = CharSet.Ansi, SetLastError = true)] |
| 178 | + private static extern int SysCtlByName(string name, out int oldp, ref IntPtr oldlenp, IntPtr newp, IntPtr newlen); |
| 179 | + |
| 180 | + /// <summary> |
| 181 | + /// Gets the total number of logical processors on a macOS host via <c>sysctlbyname("hw.logicalcpu", ...)</c>, |
| 182 | + /// the standard, stable way to query total logical CPUs on macOS. |
| 183 | + /// </summary> |
| 184 | + internal static int? GetTotalProcessorCount() |
| 185 | + { |
| 186 | + var size = new IntPtr(sizeof(int)); |
| 187 | + var result = SysCtlByName(LogicalCpuName, out var value, ref size, IntPtr.Zero, IntPtr.Zero); |
| 188 | + if (result == 0 && value > 0) |
| 189 | + { |
| 190 | + return value; |
| 191 | + } |
| 192 | + |
| 193 | + var error = Marshal.GetLastWin32Error(); |
| 194 | + Log.Warning( |
| 195 | + "sysctlbyname failed when getting total machine processor count. ErrorCode={ErrorCode}", |
| 196 | + property: error); |
| 197 | + return null; |
| 198 | + } |
| 199 | + } |
| 200 | +} |
| 201 | +#endif |
0 commit comments